﻿
Imports System.Runtime.InteropServices
Imports System.Data.SqlClient
Imports System.Threading

''' <summary>
''' 客戶信息處理
''' </summary>
''' <remarks>
''' 
''' Old version 
'''      create person:huyang
'''      Create Date: 2008-04-15
''' this new vesion
'''      Create Person:weiqi
'''      Create Date:2009-8-20
'''爲了增加代碼的靈活性，大幅度的修改原來的界面的代碼
''' </remarks>
Public Class Frm_CSReceiveInformationNew

    Implements IDServer.IDServer.IDServer

#Region " Variabled "

#Region "System Variabled Define"


    Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp

    Private WithEvents MainForm As Frm_MainForm

    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainForm
        End Get
        Set(ByVal value As Frm_MainForm)
            MainForm = value
        End Set
    End Property

    Public action_help As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp

#End Region

#Region "user variabled define"

    ''' <summary>
    ''' 窗體是否加載
    ''' </summary>
    ''' <remarks></remarks>
    Private fLoadBool As Boolean = False

    Public Fields As String

    Private HistoryTime As Date = Now()

    Private Interval As String

    Private Const MessageRefresh As String = "此銷售單曾多次來電,已顯示在列表."

    ''' <summary>
    ''' 是否是正在填充Combobox數據，是則不觸發SelectedValue事件
    ''' </summary>
    ''' <remarks></remarks>
    Private fillBool As Boolean = False


    ''' <summary>
    ''' 是否是第一次初始化網格
    ''' </summary>
    ''' <remarks></remarks>
    Private IsInitDG As Boolean = False
    ''' <summary>
    ''' 公共信息的DataSet
    ''' </summary>
    ''' <remarks></remarks>
    Dim dsInfo As DataSet = New DataSet()

    '用來優化查詢速度，同時不影響系統運行，需要合理設置這兩個時間
    '老版本數據在設定的時間前
    Dim OldVersionDateBefore As String = ModSys.GetCSDefineDate(CSDefineDates.OldVersionDateBefore)
    '新版本數據在設定的時間后
    Dim NewVersionDateAfter As String = ModSys.GetCSDefineDate(CSDefineDates.NewVersionDateAfter)

#End Region

#End Region

#Region " Methods "

#Region " Initilization "

    Private Sub Init()
        Me.txt_QuickSearch.Focus()
        Me.DateTimePicker1.Enabled = True
        Me.DateTimePicker2.Enabled = True
        Me.Label38.Text = ""
        Me.ckb_start.Checked = True
        Me.ckb_End.Checked = True
        Me.DateTimePicker1.Text = ServerDate
        Me.DateTimePicker2.Text = ServerDate

        FillComboxForEnum(Me.cbx_Complete, GetType(ModEnum.CompleteStatus))
        FillComboxForEnum(Me.cbx_CallBackStatus, GetType(ModEnum.CallBackStatus))
        FillComboxForEnum(Me.txtCompleteRemark, GetType(ModEnum.CompleteRemark))
        FillComboxForEnum(Me.txtCompleteRemark2, GetType(ModEnum.CompleteRemark))
        FillComboxForEnum(Me.cbxComplainLevel, GetType(ModEnum.ComplainLevel))
        FillComboxForEnum(Me.ComboBox1, GetType(ModEnum.ComplainLevel))
        FillCombox()
        SetEnabled_Receive(False)
        SetEnabled_BackCall(False)
        AddHandlers(New Control() {P_Top_1, Panel1, Panel4})
        Interval = System.Configuration.ConfigurationManager.AppSettings("RefreshTime").ToString() & ""
        Dim imeMode As clsIme = New clsIme()
        imeMode.AddHandler_ImeMode(New Control() {Me.Panel1, Me.Panel4, P_Top_1})
        If Val(Interval) >= 60000 Then
            Me.Timer1.Interval = Val(Interval)
        Else
            Me.Timer1.Interval = 60000
        End If
        Me.Timer1.Enabled = False
        'Me.ComboBox1.Visible = False
        lbMessageRefresh.Text = ""
    End Sub

    Private Function ReturnCaption(ByVal index As Integer) As Hashtable
        Dim Hash As New Hashtable

        Select Case index
            Case 1
                Hash.Add("fLevel1", "級別")
                Hash.Add("ReceiveCallDate", "來電日期")
                Hash.Add("ReceiveCallTime", "接時間")
                Hash.Add("FullName", "來電類別1")
                Hash.Add("PONum", "PO號碼")
                Hash.Add("fSaleOrdeNo", "銷售單號")
                Hash.Add("Contents", "內容")
                Hash.Add("ListenPsn", "接聽人")
                Hash.Add("CompleteRemark", "接OK")
                Hash.Add("LastCallBackRemark", "跟進情況")
                Hash.Add("Remark", "備注")
                Hash.Add("CustomerName", "客人姓名")
                Hash.Add("ContactPhone", "聯絡電話")
                Hash.Add("PurchaseDate", "購買日期")
                Hash.Add("GoodsName", "貨品")
                Hash.Add("GoodsDescript", "貨品描述")
                Hash.Add("DeliveryAddress", "送貨地址")

                Hash.Add("BoNum", "單號")
                'Hash.Add("ItemNo", "服務項目")

                Hash.Add("TakeTime", "所用時間")
                Hash.Add("CallBackStatus", "回複狀態")
                Hash.Add("LastCallBackTime", "複時間")
                Hash.Add("LastCallBackDate", "回複日期")
                Hash.Add("LastCallBackPsn", "回複者")
                Hash.Add("LastCompleteRemark", "複OK")
                Hash.Add("AgentCode", "來電類別2")
                Hash.Add("FullName2", "CS留言來電類別")
                'Hash.Add("CompleteStatus", "完成狀態")
                Hash.Add("SupplierName", "代理行")
                ' Hash.Add("EnName", "BarCode")
                Hash.Add("fEmployeeName", "員工")
                Hash.Add("DSCTruck", "DSC車隊")
                Hash.Add("DGKD", "DG柯打")
                Hash.Add("DGDelivery", "DG送貨")
                Hash.Add("ComplainLevel", "投訴級別")
                'Hash.Add("fOperatorPsn", "建檔者")
                'Hash.Add("fOperatorDate", "建檔日期")
                'Hash.Add("fUpdatePsn", "修改者")
                'Hash.Add("fUpdateDate", "修改日期")
            Case 2

                Hash.Add("Number", "序號")
                Hash.Add("CallBackTime", "回複時間")
                Hash.Add("CallBackDate", "回複日期")
                Hash.Add("fRemark", "內容")
                Hash.Add("CompleteRemark", "完成情況")
                Hash.Add("TakeTime", "所用時間")
                Hash.Add("CallBackPsn", "回複者")
                Hash.Add("fOperatorPsn", "建檔者")
                Hash.Add("fOperatorDate", "建檔日期")
                Hash.Add("fUpdatePsn", "修改者")
                Hash.Add("fUpdateDate", "修改日期")

            Case 3

                Hash.Add("Number", "序號")
                Hash.Add("PoNum", "PO號碼")
                Hash.Add("fSaleOrdeNo", "銷售單號")
                Hash.Add("PurchaseDate", "購買日期")
                Hash.Add("SupplierName", "供應商")
                Hash.Add("DeliveryAddress", "送貨地址")
                Hash.Add("GoodsName", "貨品型號")
                Hash.Add("GoodsDescript", "貨品描述")
                Hash.Add("ReceiveType", "來電類別")
                Hash.Add("DSCTruck", "DSC車隊")
                Hash.Add("DGDelivery", "DG送貨")
                Hash.Add("CompleteStatus", "跟進情況")
                Hash.Add("ReceiveCode", "類別編號")
                Hash.Add("Contents2", "內容")
                Hash.Add("Remark2", "備注")
                Hash.Add("fEmployeeName2", "跟進人")
                Hash.Add("DGKD", "DG柯打")
        End Select

        Return Hash
    End Function

    Private Sub FillCombox()

        Me.cbxfLevel1.Items.Add("")
        Me.cbxfLevel1.Items.Add("急")
        Me.cbxfLevel1.Items.Add("超")

    End Sub

    Private Sub ReturnInitDataSet()

        'Dim ds As DataSet = New DataSet()
        '0 來電類型表
        Dim sql As String = "select fCode,fParentCode,fName,fLevel,fType,FTypeCodes,ifRequiedChild from CS_CusterServiceTypes order by fcode " & vbCrLf

        '1代理行信息
        sql &= " select * from (" & vbCrLf
        sql &= " select AgentCode,ShortCode,AgentName,fTypeCode,AgentBrand from dbo.CS_AgentInformation where ShortCode<>''" & vbCrLf  'fTypeCode：家私行缺貨（01）行電器缺貨（03）
        sql &= " union  all" & vbCrLf
        sql &= " select  '00000','A貨','A貨','00',Null" & vbCrLf
        sql &= " union  all" & vbCrLf
        sql &= " select  '99913','電器公司送','電器公司送','00',Null" & vbCrLf
        sql &= " union  all" & vbCrLf
        sql &= " select  '99910','A貨','A貨','02',Null" & vbCrLf '公司送貨/電器缺貨  fTypeCode
        sql &= " union  all" & vbCrLf
        sql &= " select  '99911','公司送','公司送','04',Null" & vbCrLf
        sql &= " union  all" & vbCrLf
        sql &= " select  '99912','代理行送','代理行送','04',Null" & vbCrLf
        sql &= " )a order by fTypeCode,AgentCode" & vbCrLf


        '2
        sql &= " select distinct fCName=ltrim(fCName)  from dbo.BSC_Employee where Isnull(fCName,'')<>''  " & vbCrLf

        '3
        sql &= " select distinct  TruckName from dbo.BSC_Truck " & vbCrLf


        dsInfo = Exec(sql, E_ExecType.DataSet)

        dsInfo.Tables(0).TableName = "CS_CusterServiceTypes"
        dsInfo.Tables(1).TableName = "CS_AgentInformation"
        dsInfo.Tables(2).TableName = "BSC_Employee"
        dsInfo.Tables(3).TableName = "BSC_Truck"

    End Sub

    Private Sub FillServiceType(ByVal Dtab As DataTable)
        Me.fillBool = True
        Dim dataView As DataView = Dtab.DefaultView()
        dataView.RowFilter = "fLevel=0"

        Me.cbxItemParentNo.DataSource = dataView
        cbxItemParentNo.DisplayMember = "fName"
        cbxItemParentNo.ValueMember = "fCode"

        Me.fillBool = False

        Me.cbxItemParentNo.Text = ""
        Me.cbxItemParentNo.SelectedIndex = -1

    End Sub

    ''' <summary>
    ''' 代理行信息
    ''' </summary>
    ''' <param name="Dtab"></param>
    ''' <param name="RowFilter"></param>
    ''' <remarks></remarks>
    Private Sub FillAgentInformation(ByVal Dtab As DataTable, ByVal RowFilter As String)
        Me.fillBool = True
        Dim dataView As DataView = Dtab.DefaultView()
        dataView.RowFilter = RowFilter

        Me.cbxItemNo2.DataSource = dataView
        Me.cbxItemNo2.DisplayMember = "ShortCode"
        Me.cbxItemNo2.ValueMember = "AgentCode"
        Me.fillBool = False
        If Me.cbxItemNo2.Items.Count > 1 Then
            Me.cbxItemNo2.Text = ""
            Me.cbxItemNo2.SelectedIndex = -1
        End If
    End Sub

    ''' <summary>
    ''' 填充下一層節點的內容
    ''' </summary>
    ''' <param name="Dtab"></param>
    ''' <param name="RowFilter"></param>
    ''' <remarks></remarks>
    Private Sub FillAgentInformation2(ByVal combox As ComboBox, ByVal RowFilter As String)
        Me.fillBool = True
        Dim dataView As DataView = New DataView(Me.dsInfo.Tables(0))
        dataView.RowFilter = RowFilter
        combox.DataSource = dataView
        combox.DisplayMember = "fName"
        combox.ValueMember = "fCode"
        Me.fillBool = False
        If combox.Items.Count > 1 Then
            combox.Text = ""
            combox.SelectedIndex = -1
        End If
    End Sub

    Private Sub FillItemNo2(ByVal Dtab As DataTable, ByVal RowFilter As String)
        Dim dataView As DataView = Dtab.DefaultView()
        dataView.RowFilter = RowFilter

        Me.cbxItemNo2.DataSource = dataView
        Me.cbxItemNo2.DisplayMember = "fName"
        Me.cbxItemNo2.ValueMember = "fCode"

        If Me.cbxItemNo2.Items.Count > 1 Then
            Me.cbxItemNo2.Text = ""
            Me.cbxItemNo2.SelectedIndex = -1
        End If
    End Sub

    Private Sub FillEmployee(ByVal Dtab As DataTable)

        Me.cbxfEmployeeName.DataSource = Dtab
        cbxfEmployeeName.DisplayMember = "fCName"
        Me.cbxfEmployeeName.Text = ""
        Me.cbxfEmployeeName.SelectedIndex = -1 '

    End Sub

    Private Sub FillSupplierName(ByVal Dtab As DataTable)

        Dim dv As DataView = Dtab.DefaultView()

        Dim rowFilter As String = "fTypeCode in ('00','01','03')" 'fTypeCode：家私行缺貨（01）行電器缺貨（03）
        dv.RowFilter = rowFilter
        Me.cbxSupplierName.DataSource = dv
        Me.cbxSupplierName.DisplayMember = "ShortCode"
        Me.cbxSupplierName.Text = ""
        Me.cbxSupplierName.SelectedIndex = -1

    End Sub

    Private Sub FillDSCTruck(ByVal Dtab As DataTable)

        Me.cbxDSCTruck.DataSource = Dtab
        Me.cbxDSCTruck.DisplayMember = "TruckName"
        Me.cbxDSCTruck.Text = ""
        Me.cbxDSCTruck.SelectedIndex = -1

        'Me.cbxDSCTruck1.Parent = Me.DataGridView1
        Me.cbxDSCTruck1.DisplayMember = "TruckName"
        Me.cbxDSCTruck1.Visible = False
        Me.cbxDSCTruck1.DataSource = Dtab.Copy
        Me.cbxDSCTruck1.SelectedIndex = -1
    End Sub

    Public Sub ThreadExecFind()
        Dim whereExp As String = Me.GetWhereExp()
        ExecFind(whereExp)
    End Sub

    Public Sub InvokeExecFind()
        ReturnInitDataSet()
        Me.TabControl1.Invoke(New MethodInvoker(AddressOf ThreadExecFind))
    End Sub

#End Region

#Region " FillDetial "

    Private Sub FillDetail(ByVal BoNum As String)
        If isNull(BoNum) Then
            BoNum = "ErrorNums"
        End If
        'Dim Dtab As DataTable = DirectCast(Me.DGV_Master.DataSource, DataTable)
        Dim dtab As DataTable = FindBonumInfo(BoNum)
        Dim DRow() As DataRow = dtab.Select("BoNum='" & BoNum & "'")

        If DRow.Length > 0 Then

            For Each col As Control In Me.GroupBox2.Controls
                If TypeOf col Is ComboBox Then
                    CType(col, ComboBox).SelectedIndex = -1
                End If
            Next

            Me.txtBoNum.Text = DRow(0).Item("BoNum") & ""
            Me.txtReceiveCallTime.Text = DRow(0).Item("ReceiveCallTime") & ""
            Me.txtCustomerName.Text = DRow(0).Item("CustomerName") & ""
            Me.txtContactPhone.Text = DRow(0).Item("ContactPhone") & ""
            Me.txtfSaleOrdeNo.Text = DRow(0).Item("fSaleOrdeNo") & ""
            Me.cbxfLevel1.Text = DRow(0).Item("fLevel1") & ""
            If IsDate(DRow(0).Item("ReceiveCallDate")) Then
                Me.dtpReceiveCallDate.Text = DRow(0).Item("ReceiveCallDate")
            End If
            Me.tbxPO.Text = DRow(0)("PONum") & ""
            RichTextBoxContents.Text = DRow(0).Item("Contents") & ""
            Me.txtTakeTime.Text = DRow(0).Item("TakeTime") & ""
            Me.txtListenPsn.Text = DRow(0).Item("ListenPsn") & ""
            Me.txtCompleteRemark.Text = DRow(0).Item("CompleteRemark") & ""
            Me.RichTextBoxRemark.Text = DRow(0).Item("Remark") & ""

            Me.lbOperatorPsn.Text = DRow(0).Item("fOperatorPsn") & ""
            Me.lbOperatorDate.Text = DRow(0).Item("fOperatorDate") & ""

            Me.lbUpdatePsn.Text = DRow(0).Item("fUpdatePsn") & ""
            Me.lbUpdateDate.Text = DRow(0).Item("fUpdateDate") & ""


            'If (Me.cbxCustomerServiceType.Text.Trim.IndexOf("CS留言") > -1 OrElse Me.cbxCustomerServiceType.SelectedValue & "" = "1101") Then
            '    Me.cbxAgentCode.Text = DRow(0).Item("ItemParentNo2Name") & "" ''留言
            '    'ElseIf Me.cbxCustomerServiceType.Text.Trim.IndexOf("投訴") > -1 Then
            '    '    Me.cbxAgentCode.Text = DRow(0).Item("ComplainLevel") & ""  ''投訴級別
            'Else
            '    If DRow(0).Item("AgentCode") & "" = "" Then
            '        Me.cbxAgentCode.SelectedIndex = -1
            '    Else
            '        Me.cbxAgentCode.Text = DRow(0).Item("AgentCode") & "" ''代理行
            '    End If

            'End If
            Me.cbxItemParentNo.Text = DRow(0).Item("ItemParentName") & ""
            Me.cbxCustomerServiceType.Text = DRow(0).Item("ItemName") & ""

            Me.cbxAgentCode.Text = DRow(0).Item("AgentCode") & "" ''代理行

            Me.cbxItemNo2.Text = DRow(0).Item("ItemNo2Name") & ""

            If (Me.cbxItemParentNo.SelectedIndex = -1) Then
                Me.cbxItemParentNo.SelectedValue = DRow(0)("ItemParentNo") & ""
            End If
            If Me.cbxCustomerServiceType.SelectedIndex = -1 Then
                Me.cbxCustomerServiceType.SelectedValue = DRow(0)("ItemNo") & ""
            End If
            If Me.cbxAgentCode.SelectedIndex = -1 Then
                Me.cbxAgentCode.SelectedValue = DRow(0)("ItemParentNo2") & ""
            End If



            Me.txtPurchaseDate.Text = DRow(0).Item("PurchaseDate") & ""
            Me.cbxSupplierName.Text = DRow(0).Item("SupplierName") & ""
            Me.txtGoodsName.Text = DRow(0).Item("GoodsName") & ""
            Me.txtEnName.Text = DRow(0).Item("EnName") & ""
            Me.cbxfEmployeeName.Text = DRow(0).Item("fEmployeeName") & ""
            Me.cbxDSCTruck.Text = DRow(0).Item("DSCTruck") & ""
            Me.txtDGKD.Text = DRow(0).Item("DGKD") & ""
            Me.txtDGDelivery.Text = DRow(0).Item("DGDelivery") & ""

            Me.cbxComplainLevel.Text = DRow(0).Item("ComplainLevel") & ""
            Me.txtDeliveryAddress.Text = DRow(0).Item("DeliveryAddress") & ""
            Me.txtGoodsDescript.Text = DRow(0).Item("GoodsDescript") & ""

        Else
            Me.txtBoNum.Text = ""
            Me.txtReceiveCallTime.Text = ""
            Me.txtCustomerName.Text = ""
            Me.txtContactPhone.Text = ""
            Me.txtfSaleOrdeNo.Text = ""
            Me.cbxfLevel1.Text = ""
            Me.tbxPO.Text = ""
            Me.cbxItemParentNo.Text = ""
            Me.cbxCustomerServiceType.Text = ""

            Me.dtpReceiveCallDate.Text = ServerDate

            RichTextBoxContents.Text = ""
            Me.txtTakeTime.Text = ""
            Me.txtListenPsn.Text = ""
            Me.txtCompleteRemark.Text = ""
            Me.RichTextBoxRemark.Text = ""

            Me.lbOperatorPsn.Text = ""
            Me.lbOperatorDate.Text = ""

            Me.lbUpdatePsn.Text = ""
            Me.lbUpdateDate.Text = ""
            Me.cbxAgentCode.Text = ""
            Me.cbxItemNo2.Text = ""

            Me.txtPurchaseDate.Text = ""
            Me.cbxSupplierName.Text = ""
            Me.txtGoodsName.Text = ""
            Me.cbxfEmployeeName.Text = ""
            Me.cbxDSCTruck.Text = ""
            Me.txtDGKD.Text = ""
            Me.txtDGDelivery.Text = ""
            Me.cbxComplainLevel.Text = ""
            Me.txtDeliveryAddress.Text = ""
            Me.txtGoodsDescript.Text = ""

        End If

        FillDetailGrid(BoNum)

    End Sub

    Private Sub FillDetailGrid(ByVal BoNum As String)
        If isNull(BoNum) Then
            BoNum = "ErrorNums"
        End If

        Dim sql As String = ""
        Dim ds As New DataSet()


        sql &= " select BoNum,Number,CallBackTime,fRemark,CompleteRemark,TakeTime,CallBackDate," & vbCrLf
        sql &= " CallBackPsn, CompleteStatus, fOperatorPsn, fOperatorDate=Convert(varchar(10),fOperatorDate,21), fUpdatePsn, fUpdatePsn,fUpdateDate=Convert(varchar(10),fUpdateDate,21)" & vbCrLf
        sql &= " from CS_CallBackInformation where BoNum='" & BoNum & "'" & vbCrLf

        sql &= " select BoNum,PoNum,Number,fSaleOrdeNo,Contents2,PurchaseDate,SupplierName,DeliveryAddress,GoodsName," & vbCrLf
        sql &= " GoodsDescript,ReceiveCode,ReceiveType,DSCTruck,DGDelivery,CompleteStatus,fEmployeeName2,Remark2,DGKD from dbo.CS_ReceiveSaleInfo      where BoNum='" & BoNum & "'  order by Number,fSaleOrdeNo " & vbCrLf

        Try
            ds = Exec(sql, E_ExecType.DataSet)
            Me.DGV_Detail.DataSource = ds.Tables(0)
            BindDataGridViewCaption(Me.DGV_Detail, Me.ReturnCaption(2))
            FullFormatDataGridView(Me.DGV_Detail, False, False)
            Me.DGV_Detail.SelectionMode = DataGridViewSelectionMode.CellSelect
            If Me.DGV_Detail.RowCount > 0 Then
                Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(0).Cells("Number")
                Me.DGV_Detail.Columns("fRemark").Width = 300
            Else
                Me.FillCallBackDetail(BoNum)
            End If
            Me.DGV_Detail.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells)


            Me.DataGridView1.DataSource = ds.Tables(1)
            BindDataGridViewCaption(Me.DataGridView1, Me.ReturnCaption(3))

            If Me.DataGridView1.ReadOnly = False Then
                Me.TabControl2.SelectedIndex = 1
            Else
                Me.TabControl2.SelectedIndex = 0
            End If
            FullFormatDataGridView(Me.DataGridView1, False, False)
            Me.DataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect
            If IsInitDG = False Then

                For I As Integer = 2 To Me.DataGridView1.Columns.Count - 1
                    Dim Column As DataGridViewColumn = Me.DataGridView1.Columns(I)
                    Dim CellText As DataGridViewCell = New DataGridViewTextBoxCell()
                    Column.DefaultCellStyle.WrapMode = DataGridViewTriState.True
                    Column.CellTemplate = CellText
                Next

            End If
            IsInitDG = True
            SetWidthDataGrid()
        Catch ex As Exception
            MessageBox.Show(ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    End Sub

    Private Sub FillCallBackDetail(ByVal Number As String)
        Try
            Dim dtab As DataTable = DirectCast(Me.DGV_Detail.DataSource, DataTable)
            Dim DRow() As DataRow = dtab.Select("Number='" & Number & "'")
            Me.lbNumber.Text = Number

            If DRow.Length > 0 Then
                Me.txtCallBackTime.Text = DRow(0).Item("CallBackTime") & ""
                Me.dtpCallBackDate.Text = DRow(0).Item("CallBackDate") & ""
                Me.RichTextBoxfRemark2.Text = DRow(0).Item("fRemark") & ""
                Me.txtCompleteRemark2.Text = DRow(0).Item("CompleteRemark") & ""
                Me.txtTakeTime2.Text = DRow(0).Item("TakeTime") & ""
                Me.txtCallBackPsn2.Text = DRow(0).Item("CallBackPsn") & ""
            Else
                Me.txtCallBackTime.Text = ""
                Me.dtpCallBackDate.Text = ServerDate
                Me.RichTextBoxfRemark2.Text = ""
                Me.txtCompleteRemark2.Text = ""
                Me.txtTakeTime2.Text = ""
                Me.txtCallBackPsn2.Text = ""
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region " ExecFind "

    Private Function GetWhereExp()
        Dim sql As String = ""
        If Me.fLoadBool = False Then

            sql = "  where    1<>1"

        Else

            sql = "   where 1=1 "

            If Me.txt_BoNum.Text.Trim <> "" Then
                sql &= "   and BoNum like '%" & Me.txt_BoNum.Text.Trim & "%'"
            End If

            If Me.txt_fSaleOrdeNo.Text.Trim <> "" Then
                sql &= "  and fSaleOrdeNo like '%" & Me.txt_fSaleOrdeNo.Text.Trim & "%'"
            End If

            If Me.txt_CustomerName.Text.Trim <> "" AndAlso Me.txt_fEmployeeId.Text.Trim <> "" Then
                sql &= "  and ( BoNum in (select  Distinct BoNum from CS_CallBackInformation where CallBackPsn = '" & Me.txt_CustomerName.Text.Trim & "')  or ListenPsn = '" & Me.txt_fEmployeeId.Text.Trim & "')"
            Else
                If Me.txt_CustomerName.Text.Trim <> "" Then
                    'sql &= "   and CustomerName like '%" & Me.txt_CustomerName.Text.Trim & "%'"
                    sql &= "   and BoNum in (select  Distinct BoNum from CS_CallBackInformation where CallBackPsn = '" & Me.txt_CustomerName.Text.Trim & "')"
                End If
                If Me.txt_fEmployeeId.Text.Trim <> "" Then
                    sql &= "  and ListenPsn = '" & Me.txt_fEmployeeId.Text.Trim & "'"
                End If
            End If

            If Me.txt_CustomerTelphone.Text.Trim <> "" Then
                sql &= "  and ContactPhone like '%" & Me.txt_CustomerTelphone.Text.Trim & "%'"
            End If

            If Me.ckb_start.Checked = True Then

                sql &= "  and  ReceiveCallDate>='" & Format(Me.DateTimePicker1.Value, "yyy-MM-dd") & "'"

            End If
            If Me.ckb_End.Checked = True Then
                sql &= "  and  ReceiveCallDate<='" & Format(Me.DateTimePicker2.Value, "yyy-MM-dd") & "'"
            End If

            If Me.cbx_Complete.Text.Trim <> "" Then
                If Me.cbx_Complete.Text.Trim = CompleteStatus.已完成.ToString() Then
                    sql &= "  and (Charindex('ok',Isnull(LastCompleteRemark,''),0)>0 or charindex('ok',Isnull(CompleteRemark,''),0)>0) and (Charindex('跟進',Isnull(LastCompleteRemark,''),0)<=0 and  charindex('跟進',Isnull(CompleteRemark,''),0)<=0) "
                ElseIf Me.cbx_Complete.Text.Trim = CompleteStatus.未完成.ToString() Then
                    sql &= "and ((Charindex('跟進',Isnull(LastCompleteRemark,''),0)>0or charindex('跟進',Isnull(CompleteRemark,''),0)>0) or(isnull(LastCompleteRemark,'')='' and  isnull(CompleteRemark,'')=''))"
                    'sql &= "  and (Charindex('ok',Isnull(LastCompleteRemark,''),0)<=0 and  charindex('ok',Isnull(CompleteRemark,''),0)<=0) "
                ElseIf Me.cbx_Complete.Text.Trim = CompleteStatus.跟進.ToString.Trim Then
                    sql &= "  and (Charindex('跟進',Isnull(LastCompleteRemark,''),0)>0 or charindex('跟進',Isnull(CompleteRemark,''),0)>0)" 'and (Charindex('ok',Isnull(LastCompleteRemark,''),0)<=0 and  charindex('ok',Isnull(CompleteRemark,''),0)<=0) "
                Else
                    sql &= "  and (Charindex('" & Me.cbx_Complete.Text.Trim & "',Isnull(LastCompleteRemark,''),0)>0 or  charindex('" & Me.cbx_Complete.Text.Trim & "',Isnull(CompleteRemark,''),0)>0) "
                End If
            End If

            If Me.cbx_CallBackStatus.Text.Trim <> "" Then
                If Me.cbx_CallBackStatus.Text = CallBackStatus.已回複.ToString() Then
                    sql &= "  and Isnull(CallBackStatus,0)=1"
                Else
                    sql &= " and Isnull(CallBackStatus,0)=0"
                End If
            End If

            If Me.txt_ItemType.Text.Trim <> "" AndAlso Me.txt_ItemType.Text.Trim <> "全部" Then

                If Not Me.Tvw_ItemType.SelectedNode Is Nothing AndAlso Me.Tvw_ItemType.SelectedNode.Text.Trim = Me.txt_ItemType.Text.Trim Then
                    If Me.Tvw_ItemType.SelectedNode.Level = 1 Then
                        sql &= "  and ItemParentNo='" & Me.Tvw_ItemType.SelectedNode.Tag.ToString() & "" & "'"
                    ElseIf Me.Tvw_ItemType.SelectedNode.Level = 3 Then
                        sql &= "  and ItemNAme='" & Me.Tvw_ItemType.SelectedNode.Tag.ToString() & "" & "' "
                    Else
                        sql &= "  and ItemNo='" & Me.Tvw_ItemType.SelectedNode.Tag.ToString() & "" & "' "
                    End If
                Else
                    sql &= "  and (c.fName  like '%" & Me.txt_ItemType.Text.Trim & "" & "%'    or b.fName like '%" & Me.txt_ItemType.Text.Trim & "%')"
                End If

            End If

            If Me.txt_QuickSearch.Text.Trim <> "" Then

                sql &= "  and (ContactPhone like '%" & Me.txt_QuickSearch.Text.Trim & "%'  or fSaleOrdeNo like '%" & Me.txt_QuickSearch.Text.Trim & "%'    or Contents like N'%" & Me.txt_QuickSearch.Text.Trim & "%')"

            End If

            If Me.ComboBox1.Text.Trim <> "" Then
                sql &= "  and Isnull(ComplainLevel,'')='" & Me.ComboBox1.Text.Trim & "'  "
            End If

        End If
        Return sql
    End Function

    Private Sub ExecFind(ByVal whereExp As String, Optional ByVal bRefresh As Boolean = False)

        Me.Cursor = Cursors.WaitCursor

        Dim sql As String = ""

        '新版本的記錄
        sql &= " select fLevel1,ReceiveCallDate,ReceiveCallTime,FullName=(Isnull(c.fName,'') + '/' + Isnull(b.fName,'')),fSaleOrdeNo," + vbNewLine
        sql &= "         Contents,PONum,ListenPsn,CompleteRemark,LastCallBackRemark,Remark,CustomerName,ContactPhone,PurchaseDate,GoodsName," + vbNewLine
        sql &= "         GoodsDescript,DeliveryAddress," + vbNewLine
        sql &= "    BoNum,LastCompleteRemark,LastCallBackTime,a.ItemParentNo,c.fName as ItemParentName,ItemNo,b.fName as ItemName,"
        sql &= "   CompleteStatus=Convert(bit,CompleteStatus),TakeTime,AgentCode,ItemParentNo2,e.fName as ItemParentNo2Name ,ItemNo2,d.fName as ItemNo2Name,Case when Isnull(ItemNo,'')='1101' then Isnull(b.fName,'')+'/'+Isnull(e.fName,'')+'/'+Isnull(d.fName,'') else '' end  as FullName2," + vbNewLine
        sql &= "   CallBackStatus=Convert(Bit,CallBackStatus), LastCallBackDate, LastCallBackPsn,"
        sql &= "   ComplainLevel,SupplierName,EnName,fEmployeeName,DSCTruck,DGKD,DGDelivery,BillStatus, fOperatorPsn, fOperatorDate = Convert(varchar(10), fOperatorDate, 21), fUpdatePsn, fUpdateDate = Convert(varchar(10), fUpdateDate, 21)" + vbNewLine
        sql &= "  from CS_ReceiveInformation   a " & vbCrLf
        sql &= "inner join CS_CusterServiceTypes c on a.ItemParentNo=c.fCode    " + vbNewLine
        sql &= "  left join CS_CusterServiceTypes b on a.ItemNo=b.fCode " + vbNewLine
        sql &= "  left join CS_CusterServiceTypes d on a.ItemNo2=d.fCode left join CS_CusterServiceTypes e on a.ItemParentNo2=e.fCode    " & whereExp + vbNewLine
        sql += IIf(IsDate(Me.NewVersionDateAfter), " and a.ReceiveCallDate>'" + Me.NewVersionDateAfter + "'", "") + vbNewLine
        sql &= " union all " + vbNewLine

        ''查詢以前版本的記錄
        sql &= " select fLevel1,ReceiveCallDate,ReceiveCallTime,FullName=(Isnull(c.fName,'') + '/' + Isnull(b.fName,'')),fSaleOrdeNo," + vbNewLine
        sql &= "         Contents,PONum,ListenPsn,CompleteRemark,LastCallBackRemark,Remark,CustomerName,ContactPhone,PurchaseDate,GoodsName," + vbNewLine
        sql &= "         GoodsDescript,DeliveryAddress," + vbNewLine
        sql &= "    BoNum,LastCompleteRemark,LastCallBackTime,a.ItemParentNo,c.fName as ItemParentName,ItemNo,b.fName as ItemName,"
        sql &= "   CompleteStatus=Convert(bit,CompleteStatus),TakeTime,AgentCode,ItemParentNo2,e.fName as ItemParentNo2Name ,ItemNo2,d.fName as ItemNo2Name,Case when Isnull(ItemNo,'')='1101' then Isnull(b.fName,'')+'/'+Isnull(e.fName,'')+'/'+Isnull(d.fName,'') else '' end  as FullName2," + vbNewLine
        sql &= "   CallBackStatus=Convert(Bit,CallBackStatus), LastCallBackDate, LastCallBackPsn,"
        sql &= "   ComplainLevel,SupplierName,EnName,fEmployeeName,DSCTruck,DGKD,DGDelivery,BillStatus, fOperatorPsn, fOperatorDate = Convert(varchar(10), fOperatorDate, 21), fUpdatePsn, fUpdateDate = Convert(varchar(10), fUpdateDate, 21)" + vbNewLine
        sql &= "  from CS_ReceiveInformation   a " & vbCrLf
        sql &= "inner join CS_CusterServiceType c on a.ItemParentNo=c.fCode    " + vbNewLine
        sql &= "  left join CS_CusterServiceType b on a.ItemNo=b.fCode " + vbNewLine
        sql &= "  left join CS_CusterServiceType d on a.ItemNo2=d.fCode left join CS_CusterServiceType e on a.ItemParentNo2=e.fCode    " & whereExp + vbNewLine
        sql += IIf(IsDate(Me.OldVersionDateBefore), " and a.ReceiveCallDate<'" + Me.OldVersionDateBefore + "'", "") + vbNewLine

        Dim Dtab As DataTable = New DataTable()

        Try

            Dtab = Exec(sql, E_ExecType.DataTable)

            If bRefresh = True Then ''新增完之後查找是否存在銷售單重複更跟的情況
                If Dtab.Rows.Count > 1 Then
                    Me.DGV_Master.DataSource = Dtab
                    BindDataGridViewCaption(Me.DGV_Master, Me.ReturnCaption(1))
                    FullFormatDataGridView(Me.DGV_Master, False, False)
                    SetDataGridViewWidth()
                    Me.DGV_Master.Update()
                    Me.DGV_Master.Refresh()
                    Me.lbMessageRefresh.Text = MessageRefresh
                End If
                Exit Sub
            End If

            Me.DGV_Master.DataSource = Dtab
            BindDataGridViewCaption(Me.DGV_Master, Me.ReturnCaption(1))
            FullFormatDataGridView(Me.DGV_Master, False, False)
            SetDataGridViewWidth()
            Me.DGV_Master.SelectionMode = DataGridViewSelectionMode.CellSelect
            Dim isFind As Boolean = Me.DGV_Master.RowCount > 0
            Me.DGV_Master.AllowDrop = True

            If Me.fLoadBool = True Then
                Me.SetButton(ButtonType.Browse, isFind)
            Else
                Me.DGV_Master.Columns("fSaleOrdeNo").DefaultCellStyle.WrapMode = DataGridViewTriState.True
                Me.DGV_Master.Columns("Contents").DefaultCellStyle.WrapMode = DataGridViewTriState.True
                Me.DGV_Master.Columns("LastCallBackRemark").DefaultCellStyle.WrapMode = DataGridViewTriState.True
                Me.DGV_Master.Columns("Remark").DefaultCellStyle.WrapMode = DataGridViewTriState.True
                Me.FillDetail("")
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message + ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            Me.Cursor = Cursors.Default
        End Try

    End Sub


#End Region

#Region " SetEnabled "

    Private Sub SetEnabled_Receive(ByVal bEnabled)

        Dim bReadOnly As Boolean = Not (bEnabled)

        Me.txtBoNum.ReadOnly = True
        Me.txtReceiveCallTime.ReadOnly = bReadOnly
        Me.txtCustomerName.ReadOnly = bReadOnly
        Me.txtContactPhone.ReadOnly = bReadOnly
        Me.txtfSaleOrdeNo.ReadOnly = bReadOnly
        Me.tbxPO.ReadOnly = bReadOnly
        Me.cbxfLevel1.Enabled = bEnabled
        Me.cbxCustomerServiceType.Enabled = bEnabled

        Me.dtpReceiveCallDate.Enabled = bEnabled

        RichTextBoxContents.ReadOnly = bReadOnly
        RichTextBoxContents.BackColor = txtCustomerName.BackColor

        Me.txtTakeTime.ReadOnly = bReadOnly
        Me.txtListenPsn.ReadOnly = bReadOnly
        Me.txtCompleteRemark.Enabled = bEnabled
        Me.RichTextBoxRemark.ReadOnly = bReadOnly
        Me.RichTextBoxRemark.BackColor = txtCustomerName.BackColor

        cbxItemParentNo.Enabled = bEnabled
        Me.cbxAgentCode.Enabled = bEnabled

        'Me.btnComplain.Enabled = bReadOnly
        'Me.btnLessGoods.Enabled = bReadOnly
        Me.cbxItemNo2.Enabled = bEnabled

        Me.txtPurchaseDate.ReadOnly = bReadOnly
        Me.cbxSupplierName.Enabled = bEnabled
        Me.txtGoodsName.ReadOnly = bReadOnly
        Me.txtEnName.ReadOnly = bReadOnly
        Me.cbxfEmployeeName.Enabled = bEnabled
        Me.cbxDSCTruck.Enabled = bEnabled
        Me.txtDGKD.ReadOnly = bReadOnly
        Me.txtDGDelivery.ReadOnly = bReadOnly
        Me.cbxComplainLevel.Enabled = bEnabled
        Me.txtDeliveryAddress.ReadOnly = bReadOnly
        Me.txtGoodsDescript.ReadOnly = bReadOnly

    End Sub

    Private Sub SetEnabled_BackCall(ByVal bEnabled As Boolean)

        Dim bReadOnly As Boolean = Not (bEnabled)

        Me.txtCallBackTime.ReadOnly = bReadOnly
        Me.dtpCallBackDate.Enabled = bEnabled
        Me.RichTextBoxfRemark2.ReadOnly = bReadOnly
        Me.RichTextBoxfRemark2.BackColor = Me.txtCallBackTime.BackColor

        Me.txtCompleteRemark2.Enabled = bEnabled
        Me.txtTakeTime2.ReadOnly = bReadOnly
        Me.txtCallBackPsn2.ReadOnly = bReadOnly

    End Sub


    ''' <summary>
    ''' 設置按鈕狀態
    ''' </summary>
    ''' <param name="type">操作類型</param>
    ''' <param name="IsFind">是否是流覽</param>
    ''' <remarks></remarks>
    Private Sub SetButton(ByVal type As ButtonType, ByVal IsFind As Boolean)
        Try

            Select Case type
                Case ButtonType.Add
                    With MainForm
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

                Case ButtonType.Browse
                    With MainForm
                        .ToolStripAdd.Enabled = True AndAlso (action_help = IDServer.IDServer.ActionBtn.ActionHelp)
                        .ToolStripEdit.Enabled = IsFind AndAlso (action_help = IDServer.IDServer.ActionBtn.ActionHelp)
                        .ToolStripDelete.Enabled = IsFind AndAlso (action_help = IDServer.IDServer.ActionBtn.ActionHelp)
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = IsFind AndAlso (action_help = IDServer.IDServer.ActionBtn.ActionHelp)
                        .ToolStripLast.Enabled = IsFind AndAlso (action_help = IDServer.IDServer.ActionBtn.ActionHelp)
                        .ToolStripNext.Enabled = IsFind AndAlso (action_help = IDServer.IDServer.ActionBtn.ActionHelp)
                        .ToolStripPrivous.Enabled = IsFind AndAlso (action_help = IDServer.IDServer.ActionBtn.ActionHelp)
                        .ToolStripExport.Enabled = IsFind AndAlso (action_help = IDServer.IDServer.ActionBtn.ActionHelp)
                        .ToolStripImport.Enabled = True AndAlso (action_help = IDServer.IDServer.ActionBtn.ActionHelp)
                        .ToolStripPrint.Enabled = IsFind AndAlso (action_help = IDServer.IDServer.ActionBtn.ActionHelp)
                        .ToolStripFilter.Enabled = True AndAlso (action_help = IDServer.IDServer.ActionBtn.ActionHelp)
                        .ToolStripCheck.Enabled = False
                        .ToolStripComplete.Enabled = False
                        .ToolStripUnCheck.Enabled = False
                    End With

                Case ButtonType.Cancel
                    With MainForm
                        .ToolStripAdd.Enabled = True
                        .ToolStripEdit.Enabled = IsFind
                        .ToolStripDelete.Enabled = IsFind
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = IsFind
                        .ToolStripLast.Enabled = IsFind
                        .ToolStripNext.Enabled = IsFind
                        .ToolStripPrivous.Enabled = IsFind
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

                Case ButtonType.Edit
                    With MainForm
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

            End Select
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub



#End Region

#Region " AddHandler Events "

    ''' <summary>
    ''' KeyDown Event
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub TextBox_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        Try
            Select Case e.KeyCode
                Case Keys.Enter
                    If e.Shift = True Then
                        If TypeOf sender Is ComboBox Then
                            If CType(sender, ComboBox).DroppedDown = True Then
                                CType(sender, ComboBox).DroppedDown = False
                            End If
                        End If
                        Me.ProcessTabKey(False)
                        SendKeys.Send("{F4}")
                    Else
                        If TypeOf sender Is ComboBox Then
                            If CType(sender, ComboBox).DroppedDown = True Then
                                CType(sender, ComboBox).DroppedDown = False
                            End If
                        End If
                        If TypeOf sender Is TextBox AndAlso CType(sender, TextBox).Multiline = True Then
                        Else
                            Me.ProcessTabKey(True)
                            SendKeys.Send("{F4}")
                        End If
                    End If
            End Select
        Catch ex As Exception
            MsgBox("TextBox_KeyDown:" & ex.Message & ex.StackTrace, MsgBoxStyle.Critical And MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    ''' <summary>
    ''' 添加自定義事件
    ''' </summary>
    ''' <param name="Pans"></param>
    ''' <remarks></remarks>
    Private Sub AddHandlers(ByVal Pans() As Control)
        Try
            For Each Pan As Control In Pans
                For Each Ctrl As Control In Pan.Controls
                    If TypeOf Ctrl Is TextBox _
                       OrElse TypeOf Ctrl Is ComboBox _
                       OrElse TypeOf Ctrl Is DateTimePicker Then
                        AddHandler Ctrl.KeyDown, AddressOf TextBox_KeyDown
                    End If
                Next
            Next
        Catch ex As Exception
            MsgBox("AddHandlers:" & ex.Message & ex.StackTrace, MsgBoxStyle.Critical And MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

#End Region

#Region " SaveData "

    Private Function SaveReceiveData()
        Dim bSuccess As Boolean = False

        Dim BoNum As String = Me.txtBoNum.Text.Trim
        Dim ReceiveCallTime As String = Me.txtReceiveCallTime.Text.Trim
        Dim CustomerName As String = Me.txtCustomerName.Text.Trim
        Dim ContactPhone As String = Me.txtContactPhone.Text.Trim
        Dim fSaleOrdeNo As String = Me.txtfSaleOrdeNo.Text.Trim
        Dim fLevel1 As String = Me.cbxfLevel1.Text
        Dim CustomerServiceType = Me.cbxCustomerServiceType.SelectedValue & ""
        Dim ReceiveCallDate As String = Me.dtpReceiveCallDate.Text
        Dim Contents As String = Me.RichTextBoxContents.Text.Trim.Replace("'", "")
        Dim TakeTime As Double = Val(Me.txtTakeTime.Text.Trim)
        Dim ListenPsn As String = Me.txtListenPsn.Text.Trim
        Dim CompleteRemark As String = Me.txtCompleteRemark.Text.Trim.ToUpper()
        Dim Remark As String = Me.RichTextBoxRemark.Text.Trim.Replace("'", "")
        Dim CompleteStatus As Integer = IIf(CompleteRemark.ToLower.IndexOf("ok") > 0, 1, 0)
        Dim Person As String = PubUserName
        Dim ComputerName = My.Computer.Name
        Dim EnName As String = Me.txtEnName.Text.Trim

        Dim ItemParentNo As String = Me.cbxItemParentNo.SelectedValue & ""
        Dim ItemName As String = Me.cbxAgentCode.SelectedValue & ""

        Dim ItemParentNo2 As String = ""
        If TypeOf Me.cbxAgentCode.SelectedValue Is String Then
            ItemParentNo2 = Me.cbxAgentCode.SelectedValue & ""
        End If
        Dim ItemNo2 As String = Me.cbxItemNo2.SelectedValue & ""

        Dim AgentCode As String = Me.cbxAgentCode.Text.Trim
        Dim PoNum As String = Me.tbxPO.Text.Trim
        Dim PurchaseDate As String = Me.txtPurchaseDate.Text.Trim
        Dim SupplierName As String = Me.cbxSupplierName.Text.Trim
        Dim GoodsName As String = Replace_Text(Me.txtGoodsName.Text.Trim)
        Dim fEmployeeName As String = Replace_Text(Me.cbxfEmployeeName.Text.Trim)
        Dim DSCTruck As String = Me.cbxDSCTruck.Text.Trim
        Dim DGKD As String = Me.txtDGKD.Text.Trim
        Dim DGDelivery As String = Replace_Text(Me.txtDGDelivery.Text.Trim)

        Dim ComplainLevel As String = Me.cbxComplainLevel.Text.Trim
        Dim DeliveryAddress As String = Replace_Text(Me.txtDeliveryAddress.Text.Trim)
        Dim GoodsDescript As String = Replace_Text(Me.txtGoodsDescript.Text.Trim)


        Dim sql As System.Text.StringBuilder = New System.Text.StringBuilder()

        If Me.cbxItemParentNo.Text.Trim = "" Then
            ItemParentNo = ""
            CustomerServiceType = ""
            ItemParentNo2 = ""
            ItemNo2 = ""
        End If

        'CS留言的處理（原來的代碼）
        'If TypeOf Me.cbxAgentCode.SelectedValue Is String AndAlso (Me.cbxCustomerServiceType.SelectedValue & "") = "1101" Then
        '    AgentCode = ""
        'Else
        '    ItemParentNo2 = ""
        '    ItemNo2 = ""
        'End If

        '現在的版本：投訴——001005/002005
        If "|001005|002005|".Contains("|" + Me.cbxCustomerServiceType.SelectedValue.ToString + "|") Then
        Else
            ComplainLevel = ""
        End If
        '原來的版本  投訴——05
        'If Me.cbxItemParentNo.SelectedValue & "" = "05" OrElse Me.cbxAgentCode.SelectedValue & "" = "05" Then
        'Else
        '    ComplainLevel = ""
        'End If

        Me.DataGridView1.EndEdit()
        Me.DataGridView1.Update()

        ''銷售信息表
        Dim Dtab As DataTable = DirectCast(Me.DataGridView1.DataSource, DataTable)
        Dtab.AcceptChanges()
        Dim Detaidb As DataTable


        ''刪除空行
        Dim DRow() As DataRow = Dtab.Select("Isnull(fSaleOrdeNo,'')=''")
        If DRow.Length > 0 Then
            For Each Row As DataRow In DRow
                Row.Delete()
            Next
        End If
        Dtab.AcceptChanges()

        Dim fMulti As Integer = 0
        Dim fLevel As Integer = 1

        If Dtab.Rows.Count > 0 Then
            fMulti = 1
        End If

        ''（原來的代碼）CS留言的處理
        'If (Me.cbxItemParentNo.Text.Trim <> "" AndAlso Me.cbxItemParentNo.SelectedValue & "" = "11") _
        '    AndAlso (Me.cbxCustomerServiceType.Text.Trim <> "" AndAlso Me.cbxCustomerServiceType.SelectedValue & "" = "1101") Then
        '    fLevel = 2
        'End If


        Dim sqlcn As SqlConnection = GetConn()
        Dim sqlcmd As New SqlCommand()
        Dim sqlTran As SqlClient.SqlTransaction
        sqlTran = sqlcn.BeginTransaction()

        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
            '  BoNum = Exec("Exec ReturnBillNum 'CS_ReceiveInformation','BoNum','DG'", E_ExecType.ExecuteScalar) & ""

            With sqlcmd
                .CommandText = "Exec ReturnBillNum 'CS_ReceiveInformation','BoNum','DG'"
                .CommandType = CommandType.Text
                .Connection = sqlcn
                .Transaction = sqlTran
            End With
            BoNum = sqlcmd.ExecuteScalar().ToString()

            Me.txtBoNum.Text = BoNum

            sql.Append("Insert Into CS_ReceiveInformation(" & vbCrLf)
            sql.Append("BoNum,PONum,ReceiveCallTime,CustomerName,ContactPhone,fSaleOrdeNo,fLevel1,ItemNo,ItemParentNo,ItemName," & vbCrLf)
            sql.Append("ReceiveCallDate,Contents,TakeTime,ListenPsn,CompleteRemark,Remark,CompleteStatus,ItemParentNo2,ItemNo2," & vbCrLf)
            sql.Append("AgentCode,PurchaseDate,SupplierName,GoodsName,fEmployeeName,DSCTruck,DGKD,DGDelivery,ComplainLevel,DeliveryAddress,GoodsDescript,fMulti,fLevel,BillStatus,fOperatorPsn,fOperatorDate,fOperatorComputer,EnName)" & vbCrLf)
            sql.Append("values(")
            sql.Append("'" & BoNum & "',N'" + PoNum + "','" & ReceiveCallTime & "',N'" & CustomerName & "','" & ContactPhone & "','" & fSaleOrdeNo & "','" & fLevel1 & "','" & CustomerServiceType & "',  '" & ItemParentNo & "','" & ItemName & "', " & vbCrLf)
            sql.Append("'" & ReceiveCallDate & "',N'" & Contents & "','" & TakeTime & "','" & ListenPsn & "','" & CompleteRemark & "',N'" & Remark & "','" & CompleteStatus & "', '" & ItemParentNo2 & "','" & ItemNo2 & "', " & vbCrLf)
            sql.Append("'" & AgentCode & "','" & PurchaseDate & "','" & SupplierName & "','" & GoodsName & "','" & fEmployeeName & "','" & DSCTruck & "','" & DGKD & "',N'" & DGDelivery & "','" & ComplainLevel & "',N'" & DeliveryAddress & "','" & GoodsDescript & "'," & fMulti & "," & fLevel & ",'A','" & Person & "',Getdate(),'" & ComputerName & "','" & EnName & "' ")
            sql.Append(")" & vbCrLf)
        Else



            sql.Append("Update CS_ReceiveInformation set   " & vbCrLf)

            sql.Append("ReceiveCallTime='" & ReceiveCallTime & "', ")
            sql.Append("CustomerName=N'" & CustomerName & "',  ")
            sql.Append("ContactPhone='" & ContactPhone & "',  ")
            sql.Append("fSaleOrdeNo='" & fSaleOrdeNo & "',  ")
            sql.Append("fLevel1='" & fLevel1 & "', ")
            sql.Append("ItemParentNo='" & ItemParentNo & "',")
            sql.Append("ItemNo='" & CustomerServiceType & "' ,")
            sql.Append("ItemName='" & ItemName & "' ,")
            sql.Append("ReceiveCallDate='" & ReceiveCallDate & "',")
            sql.Append("Contents= N'" & Contents & "',")
            sql.Append("TakeTime='" & TakeTime & "',")
            sql.Append("ListenPsn='" & ListenPsn & "',")
            sql.Append("CompleteRemark='" & CompleteRemark & "',")
            sql.Append("AgentCode='" & AgentCode & "',")
            sql.Append("PoNum=N'" + PoNum + "',")
            sql.Append("PurchaseDate='" & PurchaseDate & "',")
            sql.Append("SupplierName='" & SupplierName & "',")
            sql.Append("GoodsName='" & GoodsName & "',")
            sql.Append("fEmployeeName='" & fEmployeeName & "',")
            sql.Append("DSCTruck='" & DSCTruck & "',")
            sql.Append("DGKD='" & DGKD & "',")
            sql.Append("DGDelivery=N'" & DGDelivery & "',")
            sql.Append("ComplainLevel='" & ComplainLevel & "',")
            sql.Append("DeliveryAddress=N'" & DeliveryAddress & "',")
            sql.Append("GoodsDescript='" & GoodsDescript & "',")

            sql.Append("ItemParentNo2='" & ItemParentNo2 & "',")
            sql.Append("ItemNo2='" & ItemNo2 & "',")
            sql.Append("Remark=N'" & Remark & "',")
            sql.Append("CompleteStatus=" & CompleteStatus & ",")

            sql.Append("fMulti=" & fMulti & " ,")
            sql.Append("fLevel=" & fLevel & ",")
            sql.Append("fUpdatePsn='" & Person & "',")
            sql.Append("fUpdateDate=Getdate(),")
            sql.Append("EnName='" & EnName & "',")
            sql.Append("fUpdateComputer='" & ComputerName & "'" & vbCrLf)

            sql.Append("where BoNum='" & BoNum & "' " & vbCrLf)

        End If

        sql.Append(" Delete CS_ReceiveSaleInfo where Isnull(BoNum,'')='" & BoNum & "'  " & vbCrLf)

        Try
            If BoNum = "" Then
                MessageBox.Show("單號不能為空。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Return False
            End If

            'Exec(sql.ToString(), E_ExecType.ExecuteNonQuery, True)


            With sqlcmd
                .CommandText = sql.ToString()
                .CommandType = CommandType.Text
                .Connection = sqlcn
                .Transaction = sqlTran
                .ExecuteNonQuery()
            End With

            Detaidb = Me.ReturnDataTable(Dtab, BoNum)

            Dim SqlCopy As SqlBulkCopy = New SqlBulkCopy(sqlcn, SqlBulkCopyOptions.Default, sqlTran)
            SqlCopy.BatchSize = 100
            SqlCopy.DestinationTableName = "CS_ReceiveSaleInfo"
            SqlCopy.WriteToServer(Detaidb)

            sqlTran.Commit()

        Catch ex As Exception
            sqlTran.Rollback()
            bSuccess = False
            WriteApplicationLog(ex.Message + vbNewLine + vbNewLine, EventType.Failure)
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
                MessageBox.Show(My.resources.ErrAdd & "請重新點保存。" + vbNewLine + ex.Message + vbNewLine + vbNewLine + ex.InnerException.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                Return False
            Else
                MessageBox.Show(My.resources.ErrEdit & ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If
        End Try

        UpdateData(BoNum, PoNum, ReceiveCallTime, CustomerName, ContactPhone, fSaleOrdeNo, _
                             CustomerServiceType, Me.cbxCustomerServiceType.Text.Trim, ItemParentNo, Me.cbxItemParentNo.Text.Trim, Me.cbxItemParentNo.Text.Trim & "/" & Me.cbxCustomerServiceType.Text, ReceiveCallDate, Contents, TakeTime, ListenPsn, CompleteRemark, _
                             Remark, CompleteStatus, Person, AgentCode, ItemParentNo2, ItemNo2, Me.cbxAgentCode.Text.Trim, Me.cbxItemNo2.Text.Trim, _
                             PurchaseDate, SupplierName, GoodsName, fEmployeeName, DSCTruck, DGKD, DGDelivery, ComplainLevel, DeliveryAddress, GoodsDescript, fLevel1)

        bSuccess = True
        If bSuccess = True Then
            MessageBox.Show(IIf(ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd, My.resources.Addsuccess, My.resources.EditSuccess), Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If

        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
            If fSaleOrdeNo.Trim.Length > 4 Then
                'Dim whereExp As String = " where 1=1   and Isnull(fSaleOrdeNo,'') ='" & fSaleOrdeNo.Trim & "'"

                Dim whereExp As String = ""
                whereExp &= "  where 1=1  "

                Dim Textstr As System.Text.StringBuilder = New System.Text.StringBuilder()



                If fSaleOrdeNo.IndexOf(",") > 0 Then
                    Dim A() As String = fSaleOrdeNo.Split(",")
                    For Each str1 As String In A
                        If str1.Trim.Length > 3 Then
                            If Textstr.ToString().Trim() <> "" Then
                                Textstr.Append("   or    ")
                            End If
                            Textstr.Append("      fSaleOrdeNo like  '%" & str1.Trim & "%' ")
                        End If
                    Next
                    If Textstr.ToString() <> "" Then
                        whereExp &= "  and (" & Textstr.ToString() & ")"
                    Else
                        whereExp &= "  and 1<>1 "
                    End If

                ElseIf fSaleOrdeNo.IndexOf("/") > 0 Then

                    Dim B() As String = fSaleOrdeNo.Split("/")
                    For Each str1 As String In B
                        If str1.Trim.Length > 3 Then
                            If Textstr.ToString().Trim() <> "" Then
                                Textstr.Append("   or    ")
                            End If
                            Textstr.Append("      fSaleOrdeNo like  '%" & str1.Trim & "%' ")
                        End If
                    Next
                    If Textstr.ToString() <> "" Then
                        whereExp &= "  and (" & Textstr.ToString() & ")"
                    Else
                        whereExp &= "  and 1<>1 "
                    End If
                ElseIf fSaleOrdeNo.IndexOf("\") > 0 Then
                    Dim B() As String = fSaleOrdeNo.Split("\")
                    For Each str1 As String In B
                        If str1.Trim.Length > 3 Then
                            If Textstr.ToString().Trim() <> "" Then
                                Textstr.Append("   or    ")
                            End If
                            Textstr.Append("      fSaleOrdeNo like  '%" & str1.Trim & "%' ")
                        End If
                    Next
                    If Textstr.ToString() <> "" Then
                        whereExp &= "  and (" & Textstr.ToString() & ")"
                    Else
                        whereExp &= "  and 1<>1 "
                    End If
                ElseIf fSaleOrdeNo.IndexOf(" ") > 0 Then
                    Dim B() As String = fSaleOrdeNo.Split(" ")
                    For Each str1 As String In B
                        If str1.Trim.Length > 4 Then
                            If Textstr.ToString().Trim() <> "" Then
                                Textstr.Append("   or    ")
                            End If
                            Textstr.Append("      fSaleOrdeNo like  '%" & str1.Trim & "%' ")
                        End If
                    Next
                    If Textstr.ToString() <> "" Then
                        whereExp &= "  and (" & Textstr.ToString() & ")"
                    Else
                        whereExp &= "  and 1<>1 "
                    End If
                Else
                    whereExp &= "  and fSaleOrdeNo like '%" & fSaleOrdeNo & "%' "
                End If

                ExecFind(whereExp, True)
            End If
        End If
        Me.DataGridView1.DataSource = Detaidb
        For Each col As DataGridViewColumn In Me.DataGridView1.Columns
            If col.Name.Equals("Contents2", StringComparison.InvariantCultureIgnoreCase) Then
                col.DisplayIndex = 4
            End If
        Next
        Me.DataGridView1.Update()
        Me.DataGridView1.Refresh()
        ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
        SetButton(ButtonType.Browse, True)
        Me.SetEnabled_Receive(False)
        SetDataGridEnabled(False)
        If Me.DGV_Master.RowCount > 0 Then
            Me.DGV_Master.CurrentCell = Me.DGV_Master.Rows(Me.DGV_Master.RowCount - 1).Cells("LastCallBackTime")
        End If
        Return bSuccess
    End Function

    Private Function Validated1() As Boolean

        Dim AgentCode As String = ""

        If Not Me.cbxAgentCode.SelectedValue Is Nothing Then
            AgentCode = Me.cbxAgentCode.SelectedValue.ToString
        End If

        If Me.cbxItemParentNo.Text.Trim = "" AndAlso Me.cbxItemParentNo.SelectedValue Is Nothing Then
            MessageBox.Show("來電類別不能為空。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Me.cbxItemParentNo.Focus()
            SendKeys.Send("{F4}")
            Return False
        End If

        If Me.cbxCustomerServiceType.Text.Trim = "" AndAlso Me.cbxCustomerServiceType.SelectedValue Is Nothing Then
            MessageBox.Show("來電類別不能為空。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Me.cbxCustomerServiceType.Focus()
            SendKeys.Send("{F4}")
            Return False
        ElseIf dsInfo.Tables(0).Select("fCode='" + Me.cbxCustomerServiceType.SelectedValue.ToString + "' and IfRequiedChild =true ").Length > 0 _
        AndAlso (isNull(Me.cbxAgentCode.Text.Trim) Or Me.cbxAgentCode.SelectedValue Is Nothing) Then
            MessageBox.Show(Me.cbxCustomerServiceType.Text + ",   請選擇小類", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Me.cbxAgentCode.Focus()
            SendKeys.Send("{F4}")
            Return False
        End If

        If "|001002|001005|002002|002005|".Contains("|" + Me.cbxCustomerServiceType.SelectedValue.ToString + "|") Then ''查送貨/投訴
            If Me.cbxSupplierName.Text.Trim = "" Then
                MessageBox.Show("代理行不能為空。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Me.cbxSupplierName.Focus()
                SendKeys.Send("{F4}")
                Return False
            End If
        End If

        If Me.txtReceiveCallTime.Text.Trim <> "" AndAlso IsDate(Me.txtReceiveCallTime.Text.Trim) = False Then
            MessageBox.Show("輸入時間有誤，請重新輸入。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Me.txtReceiveCallTime.Focus()
            Return False
        End If

        If txtCompleteRemark.Text.Trim = CompleteRemark.AMY跟進.ToString Then

            Dim Hash As New Hashtable
            Hash.Add("001002001", "家私(公司送)") ''家私(公司送)
            Hash.Add("001002003", "電器(公司送)")
            Hash.Add("001002011", "家私跟進手尾")
            Hash.Add("001002012", "電器跟進手尾")
            Hash.Add("002002001", "家私(公司送)") ''家私(公司送)
            'Hash.Add("002002003", "電器(公司送)")
            'Hash.Add("002002011", "家私跟進手尾")
            'Hash.Add("002002012", "電器跟進手尾")

            If (Not Me.cbxAgentCode.SelectedValue Is Nothing) AndAlso Hash.ContainsKey(Me.cbxAgentCode.SelectedValue.ToString) = True Then
                If cbxfEmployeeName.Text.Trim = "" Then
                    MessageBox.Show("跟進人不能為空。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Warning)
                    cbxfEmployeeName.Focus()
                    cbxfEmployeeName.DroppedDown() = True
                    Return False
                End If
            End If
        End If

        'If Me.cbxAgentCode.Text = "投訴傢俬質量（填投訴表格）" And Me.cbxSupplierName.Text = "A貨" And Me.cbxDSCTruck.Text.ToString.Trim = String.Empty Then
        '    MessageBox.Show("請選擇DSC車隊", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
        '    Me.cbxDSCTruck.Focus()
        '    Me.cbxDSCTruck.DroppedDown() = True
        '    Return False
        'End If

        '請填寫 D G 送 貨 （送貨時間）002005013|
        If "|001005013|".Contains("|" + AgentCode + "|") _
        And Me.txtDGDelivery.Text.ToString.Trim = String.Empty Then
            MessageBox.Show("請填寫" + Me.cbxAgentCode.Text, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.txtDGDelivery.Focus()
            Return False
        End If

        '對於來電進行控制，而對留言沒有該要求；原因是留言中客人可能沒有講清楚，此時不能確定到底屬於哪一類
        If "|001|004|".Contains("|" + Me.cbxItemParentNo.SelectedValue.ToString + "|") Then
            If Me.cbxCustomerServiceType.Text = "投訴" And Me.cbxAgentCode.Text = "投訴傢俬質量（填投訴表格）" And Me.cbxSupplierName.Text = "A貨" And Me.cbxDSCTruck.Text = "" Then
                MessageBox.Show("請選擇DSC車隊", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.cbxDSCTruck.DroppedDown() = True
                Return False
            End If

            If Me.cbxCustomerServiceType.Text = "投訴" And Me.cbxAgentCode.Text = "投訴傢俬質量（填投訴表格）" And Me.cbxSupplierName.Text = "A貨" And Me.txtDGDelivery.Text = "" Then
                MessageBox.Show("請填寫DG送貨", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.txtDGDelivery.Focus()
                Return False
            End If

            If Me.cbxCustomerServiceType.Text = "投訴" And Me.cbxAgentCode.Text = "投訴電器產品質量（填投訴表格）" And Me.cbxDSCTruck.Text = "" Then
                MessageBox.Show("請選擇DSC車隊", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.cbxDSCTruck.DroppedDown() = True
                Return False
            End If

            If Me.cbxCustomerServiceType.Text = "投訴" And Me.cbxAgentCode.Text = "投訴電器產品質量（填投訴表格）" And Me.txtDGDelivery.Text = "" Then
                MessageBox.Show("請填寫DG送貨", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.txtDGDelivery.Focus()
                Return False
            End If

            If Me.cbxCustomerServiceType.Text = "投訴" And Me.cbxAgentCode.Text = "投訴售貨員態度（填投訴表格）" And Me.cbxfEmployeeName.Text = "" Then
                MessageBox.Show("請選擇員工姓名", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.cbxfEmployeeName.DroppedDown() = True
                Return False
            End If

            If Me.cbxCustomerServiceType.Text = "投訴" And Me.cbxAgentCode.Text = "投訴服務部職員（填投訴表格）" And Me.cbxfEmployeeName.Text = "" Then
                MessageBox.Show("請選擇員工姓名", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.cbxfEmployeeName.DroppedDown() = True
                Return False
            End If

            If Me.cbxCustomerServiceType.Text = "投訴" And Me.cbxAgentCode.Text = "投訴送貨部職員（填投訴表格）" And Me.cbxfEmployeeName.Text = "" Then
                MessageBox.Show("請選擇員工姓名", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.cbxfEmployeeName.DroppedDown() = True
                Return False
            End If

            If Me.cbxCustomerServiceType.Text = "投訴" And Me.cbxAgentCode.Text = "投訴其他員工（填投訴表格）" And Me.cbxfEmployeeName.Text = "" Then
                MessageBox.Show("請選擇員工姓名", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.cbxfEmployeeName.DroppedDown() = True
                Return False
            End If

            If Me.cbxCustomerServiceType.Text = "投訴" And Me.cbxAgentCode.Text = "投訴送貨時間" And Me.cbxDSCTruck.Text = "" Then
                MessageBox.Show("請選擇DSC車隊", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.cbxDSCTruck.DroppedDown() = True
                Return False
            End If

            If Me.cbxCustomerServiceType.Text = "投訴" And Me.cbxAgentCode.Text = "投訴送貨司機（填投訴表格）" And Me.cbxDSCTruck.Text = "" Then
                MessageBox.Show("請選擇DSC車隊", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.cbxDSCTruck.DroppedDown() = True
                Return False
            End If
        End If

        'If Me.cbxCustomerServiceType.Text.Trim <> "" Then
        '    If ("|1102|1103|1104|1201|1202|1203|").Contains("|" + Me.cbxCustomerServiceType.SelectedValue.ToString + "|") Then
        '        If Me.cbxAgentCode.Text = "" Then
        '            MessageBox.Show("請填寫完整來電類別", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        '            Me.cbxAgentCode.DroppedDown() = True
        '            Return False
        '        End If
        '    End If
        'End If


        If Me.txtCompleteRemark.Text = "AMY跟進" And cbxAgentCode.Text.Equals("電器(行送)", StringComparison.InvariantCultureIgnoreCase) Then
            If Me.tbxPO.Text.Trim.Length = 0 Then
                Msg.MsgOK("PO號碼不能為空", "", MessageBoxIcon.Information)
                Me.tbxPO.Focus()
                Return False
            End If
        End If

        '控制維修部來電
        If Me.txtCompleteRemark.Text = "AMY跟進" Then
            ''維修部留言（維修部來電）|003003|
            If "|004002|".Contains("|" + Me.cbxCustomerServiceType.SelectedValue.ToString + "|") Then
                '落維修單 (|003003001)
                If "|004002001|".Contains("|" + AgentCode + "|") Then
                    If Me.txtPurchaseDate.TextLength <= 0 Then
                        MessageBox.Show("購買日期不能為空", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                        Me.txtPurchaseDate.Focus()
                        Return False
                    End If
                    If Me.cbxSupplierName.Text.Trim.Length <= 0 Then
                        MessageBox.Show("代理行/牌子不能為空", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                        Me.cbxSupplierName.DroppedDown() = True
                        Return False
                    End If

                    If Me.txtGoodsName.TextLength <= 0 Then
                        MessageBox.Show("貨品型號不能為空", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                        Me.txtGoodsName.Focus()
                        Return False
                    End If

                    If Me.txtDeliveryAddress.TextLength <= 0 Then
                        MessageBox.Show("送貨地址不能為空", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                        Me.txtDeliveryAddress.Focus()
                        Return False
                    End If
                End If
                '查維修進度(003003003|)
                If "|004002003|".Contains("|" + AgentCode + "|") Then
                    If Me.cbxSupplierName.Text.Trim.Length <= 0 Then
                        MessageBox.Show("代理行/牌子不能為空", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                        Me.cbxSupplierName.DroppedDown() = True
                        Return False
                    End If
                    If Me.txtGoodsName.TextLength <= 0 Then
                        MessageBox.Show("貨品型號不能為空", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                        Me.txtGoodsName.Focus()
                        Return False
                    End If
                End If
                '查詢故障及使用方法(003003004|003003005|)
                If "|004002004|004002005|".Contains("|" + AgentCode + "|") Or _
               AgentCode & "" = "004002005" Then
                    If Me.cbxSupplierName.Text.Trim.Length <= 0 Then
                        MessageBox.Show("代理行/牌子不能為空", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                        Me.cbxSupplierName.DroppedDown() = True
                        Return False
                    End If
                    If Me.txtGoodsName.TextLength <= 0 Then
                        MessageBox.Show("貨品型號不能為空", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                        Me.txtGoodsName.Focus()
                        Return False
                    End If
                    If Me.txtCustomerName.TextLength <= 0 Then
                        MessageBox.Show("顧客姓名不能為空", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                        Me.txtCustomerName.Focus()
                        Return False
                    End If
                    If Me.txtContactPhone.TextLength <= 0 Then
                        MessageBox.Show("顧客電話不能為空", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                        Me.txtContactPhone.Focus()
                        Return False
                    End If
                End If

            End If

            '偉倫安裝(003004|003004003|)
            If "|004003|".Contains("|" + Me.cbxCustomerServiceType.SelectedValue.ToString + "|") And _
            Not "|004003003|".Contains("|" + AgentCode + "|") Then
                If Me.txtPurchaseDate.TextLength <= 0 Then
                    MessageBox.Show("購買日期不能為空", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Me.txtPurchaseDate.Focus()
                    Return False
                End If
                If Me.cbxSupplierName.Text.Trim.Length <= 0 Then
                    MessageBox.Show("代理行/牌子不能為空", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Me.cbxSupplierName.DroppedDown() = True
                    Return False
                End If
                If Me.txtGoodsName.TextLength <= 0 Then
                    MessageBox.Show("貨品型號不能為空", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Me.txtGoodsName.Focus()
                    Return False
                End If
                If Me.txtGoodsDescript.TextLength <= 0 Then
                    MessageBox.Show("貨品描述不能為空", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Me.txtGoodsDescript.Focus()
                    Return False
                End If
                If Me.txtDGDelivery.TextLength <= 0 Then
                    MessageBox.Show("DG送貨不能為空", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Me.txtDGDelivery.Focus()
                    Return False
                End If
            End If
        End If
        Return True
    End Function

    Private Function UpdateData(ByVal BoNum As String, ByVal PoNum As String, ByVal ReceiveCallTime As String, ByVal CustomerName As String, ByVal ContactPhone As String, _
                                                     ByVal fSaleOrdeNo As String, ByVal ItemNo As String, ByVal ItemName As String, ByVal ItemParentNo As String, ByVal ItemParentName As String, _
                                                     ByVal FullName As String, ByVal ReceiveCallDate As String, ByVal Contents As String, ByVal TakeTime As String, ByVal ListenPsn As String, _
                                                     ByVal CompleteRemark As String, ByVal Remark As String, ByVal CompleteStatus As Integer, ByVal Person As String, ByVal AgentCode As String, _
                                                     ByVal ItemParentNo2 As String, ByVal ItemNo2 As String, ByVal ItemParentNo2Name As String, ByVal ItemNo2Name As String, _
                                                     ByVal PurchaseDate As String, ByVal SupplierName As String, ByVal GoodsName As String, ByVal fEmployeeName As String, ByVal DSCTruck As String, ByVal DGKD As String, ByVal DGDelivery As String, _
                                                      ByVal ComplainLevel As String, ByVal DeliveryAddress As String, ByVal GoodsDescript As String, ByVal fLevel1 As String) As Boolean
        Dim bSuccess As Boolean = False

        Dim Dtab As DataTable = DirectCast(Me.DGV_Master.DataSource, DataTable)

        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
            Dim Row As DataRow = Dtab.NewRow()
            Row("BoNum") = BoNum
            Row("ReceiveCallTime") = ReceiveCallTime
            Row("CustomerName") = CustomerName
            Row("ContactPhone") = ContactPhone
            Row("fSaleOrdeNo") = fSaleOrdeNo
            Row("PONum") = PoNum
            Row("ItemNo") = ItemNo
            Row("ItemName") = ItemName
            Row("ItemParentNo") = ItemParentNo
            Row("ItemParentName") = ItemParentName
            Row("FullName") = FullName
            Row("ReceiveCallDate") = ReceiveCallDate
            Row("Contents") = Contents
            Row("TakeTime") = TakeTime
            Row("ListenPsn") = ListenPsn
            Row("CompleteRemark") = CompleteRemark
            Row("Remark") = Remark
            Row("CompleteStatus") = CompleteStatus
            Row("BillStatus") = "A"
            Row("fOperatorPsn") = Person
            Row("fOperatorDate") = ServerDate
            Row("AgentCode") = AgentCode
            Row("ItemNo2") = ItemNo2
            Row("ItemParentNo2") = ItemParentNo2
            Row("ItemParentNo2Name") = ItemParentNo2Name
            Row("ItemNo2Name") = ItemNo2Name
            Row("FullName2") = ItemName & "/" & ItemParentNo2Name & "/" & ItemNo2

            Row("PurchaseDate") = PurchaseDate
            Row("SupplierName") = SupplierName
            Row("GoodsName") = GoodsName
            Row("fEmployeeName") = fEmployeeName
            Row("DSCTruck") = DSCTruck
            Row("DGKD") = DGKD
            Row("DGDelivery") = DGDelivery
            Row("ComplainLevel") = ComplainLevel
            Row("DeliveryAddress") = DeliveryAddress
            Row("GoodsDescript") = GoodsDescript
            Row("fLevel1") = fLevel1

            Dtab.Rows.Add(Row)

        Else

            Dim DRow() As DataRow = Dtab.Select("BoNum='" & BoNum & "'")

            If DRow.Length > 0 Then
                Dim Row As DataRow = DRow(0)

                Row("ReceiveCallTime") = ReceiveCallTime
                Row("CustomerName") = CustomerName
                Row("ContactPhone") = ContactPhone
                Row("fSaleOrdeNo") = fSaleOrdeNo
                Row("PONum") = PoNum
                Row("ItemNo") = ItemNo
                Row("ItemName") = ItemName
                Row("ItemParentNo") = ItemParentNo
                Row("ItemParentName") = ItemParentName
                Row("FullName") = FullName
                Row("ReceiveCallDate") = ReceiveCallDate
                Row("Contents") = Contents
                Row("TakeTime") = TakeTime
                Row("ListenPsn") = ListenPsn
                Row("CompleteRemark") = CompleteRemark
                Row("Remark") = Remark
                Row("CompleteStatus") = CompleteStatus
                Row("AgentCode") = AgentCode
                Row("ItemNo2") = ItemNo2
                Row("ItemParentNo2") = ItemParentNo2
                Row("ItemParentNo2Name") = ItemParentNo2Name
                Row("ItemNo2Name") = ItemNo2Name
                Row("FullName2") = ItemName & "/" & ItemParentNo2Name & "/" & ItemNo2
                Row("fUpdatePsn") = Person
                Row("fUpdateDate") = ServerDate

                Row("PurchaseDate") = PurchaseDate
                Row("SupplierName") = SupplierName
                Row("GoodsName") = GoodsName
                Row("fEmployeeName") = fEmployeeName
                Row("DSCTruck") = DSCTruck
                Row("DGKD") = DGKD
                Row("DGDelivery") = DGDelivery
                Row("ComplainLevel") = ComplainLevel
                Row("DeliveryAddress") = DeliveryAddress
                Row("GoodsDescript") = GoodsDescript
                Row("fLevel1") = fLevel1
            End If

        End If

        Dtab.AcceptChanges()
        Me.DGV_Master.Update()
        Me.DGV_Master.Refresh()
        bSuccess = True
        Return bSuccess
    End Function

    Private Function SaveCallBackData() As Boolean

        Dim bSuccess As Boolean = False

        Dim BoNum As String = Me.txtBoNum.Text.Trim
        Dim Number As String = Me.lbNumber.Text
        Dim CallBackTime As String = txtCallBackTime.Text.Trim
        Dim CallBackDate As String = Me.dtpCallBackDate.Text.Trim
        Dim fRemark As String = RichTextBoxfRemark2.Text.Trim
        Dim CompleteRemark As String = txtCompleteRemark2.Text.Trim.ToUpper()
        Dim TakeTime As Double = Val(txtTakeTime2.Text.Trim())
        Dim CallBackPsn As String = txtCallBackPsn2.Text.Trim

        Dim CompleteStatus As Integer = IIf(CompleteRemark.ToLower().IndexOf("ok") > 0, 1, 0)
        Dim Person As String = PubUserName

        Dim sql As New System.Text.StringBuilder()


        If action_help = IDServer.IDServer.ActionBtn.ActionAdd Then

            '有錯誤，所以修改Dim txt As String = "select  left('000'+ltrim(Isnull(Max(Number),0)+1),4) from CS_CallBackInformation where BoNum='" & BoNum & "' "
            Dim txt As String = " select dbo.PadLeft( Convert( int, isnull(max(number),'0000')+1 ),4,'0') from CS_CallBackInformation where BoNum='" & BoNum & "' "
            Number = Exec(txt, E_ExecType.ExecuteScalar) & ""
            Me.lbNumber.Text = Number
            sql.Append("Insert Into CS_CallBackInformation(" & vbCrLf)
            sql.Append("BoNum,Number,CallBackTime,CallBackDate,fRemark,CompleteRemark,TakeTime," & vbCrLf)
            sql.Append("CallBackPsn,CompleteStatus,fOperatorPsn,fOperatorDate,fOperatorComputer")
            sql.Append(")" & vbCrLf)
            sql.Append("values(" & vbCrLf)
            sql.Append("'" & BoNum & "','" & Number & "','" & CallBackTime & "','" & CallBackDate & "',N'" & fRemark & "','" & CompleteRemark & "'," & TakeTime & ",")
            sql.Append("'" & CallBackPsn & "','" & CompleteStatus & "','" & Person & "',Convert(varchar(21),Getdate(),21),'" & My.Computer.Name & "'")
            sql.Append(")" & vbCrLf)

        Else

            sql.Append("Update CS_CallBackInformation set " & vbCrLf)
            sql.Append("CallBackTime='" & CallBackTime & "',")
            sql.Append("CallBackDate='" & CallBackDate & "',")
            sql.Append("fRemark=N'" & fRemark & "',")
            sql.Append("CompleteRemark=N'" & CompleteRemark & "',")
            sql.Append("TakeTime=" & TakeTime & ",")
            sql.Append("CallBackPsn='" & CallBackPsn & "',")
            sql.Append("CompleteStatus=" & CompleteStatus & ",")
            sql.Append("fUpdatePsn='" & Person & "',")
            sql.Append("fUpdateDate=Convert(varchar(21),Getdate(),21)")
            sql.Append("where BoNum='" & BoNum & "' and Number='" & Number & "' " & vbCrLf)

        End If

        ''更新CS_ReceiveInformation
        sql.Append("Update CS_ReceiveInformation set " & vbCrLf)
        sql.Append("CallBackStatus=1,")
        sql.Append("LastCallBackTime='" & CallBackTime & "',")
        sql.Append("LastCallBackDate='" & CallBackDate & "', ")
        sql.Append("LastCallBackPsn='" & CallBackPsn & "',")
        sql.Append("CompleteStatus=" & CompleteStatus & ",")
        sql.Append("LastCompleteRemark=N'" & CompleteRemark & "',")
        sql.Append("LastCallBackRemark=N'" & fRemark & "'")
        sql.Append("where BoNum='" & BoNum & "' " & vbCrLf)

        Try

            Exec(sql.ToString(), E_ExecType.ExecuteNonQuery)
            UpdateCallBackData(BoNum, Number, CallBackTime, CallBackDate, fRemark, _
                                                CompleteRemark, TakeTime, CallBackPsn, CompleteStatus, Person)

            bSuccess = True
        Catch ex As Exception
            bSuccess = False
            MessageBox.Show("保存失敗。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

        If bSuccess = True Then
            MessageBox.Show("保存成功", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
        Me.SetEnabled_BackCall(False)
        action_help = IDServer.IDServer.ActionBtn.ActionHelp
        Return bSuccess
    End Function

    Private Function UpdateCallBackData(ByVal BoNum As String, ByVal Number As String, ByVal CallBackTime As String, ByVal CallBackDate As String, ByVal fRemark As String, ByVal CompleteRemark As String, ByVal TakeTime As Double, _
                                                                    ByVal CallBackPsn As String, ByVal CompleteStatus As Int32, ByVal Person As String) As Boolean
        Dim bSuccess As Boolean = False
        Dim tab As DataTable = DirectCast(Me.DGV_Detail.DataSource, DataTable)
        Dim master As DataTable = DirectCast(Me.DGV_Master.DataSource, DataTable)

        If action_help = IDServer.IDServer.ActionBtn.ActionAdd Then
            Dim Row As DataRow = tab.NewRow()
            Row("BoNum") = BoNum
            Row("Number") = Number
            Row("CallBackTime") = CallBackTime
            Row("CallBackDate") = CallBackDate
            Row("fRemark") = fRemark
            Row("CompleteRemark") = CompleteRemark
            Row("TakeTime") = TakeTime
            Row("CallBackPsn") = CallBackPsn
            Row("CompleteStatus") = CompleteStatus
            Row("fOperatorPsn") = Person
            Row("fOperatorDate") = ServerDate

            tab.Rows.Add(Row)

        Else

            Dim DRow() As DataRow = tab.Select("BoNum='" & BoNum & "'  and Number='" & Number & "'")
            If DRow.Length > 0 Then

                Dim Row As DataRow = DRow(0)
                Row("CallBackTime") = CallBackTime
                Row("CallBackDate") = CallBackDate
                Row("fRemark") = fRemark
                Row("CompleteRemark") = CompleteRemark
                Row("TakeTime") = TakeTime
                Row("CallBackPsn") = CallBackPsn
                Row("CompleteStatus") = CompleteStatus
                Row("fUpdatePsn") = Person
                Row("fUpdateDate") = ServerDate

            End If
        End If

        Dim SRow() As DataRow = master.Select("BoNum='" & BoNum & "'")
        If SRow.Length > 0 Then

            SRow(0).Item("CallBackStatus") = 1
            SRow(0).Item("LastCallBackTime") = CallBackTime
            SRow(0).Item("LastCallBackDate") = CallBackDate
            SRow(0).Item("LastCallBackPsn") = CallBackPsn
            SRow(0).Item("CompleteStatus") = CompleteStatus
            SRow(0).Item("LastCallBackRemark") = fRemark
            SRow(0).Item("LastCompleteRemark") = CompleteRemark
        End If

        tab.AcceptChanges()
        master.AcceptChanges()

        Me.DGV_Detail.Update()
        Me.DGV_Detail.Refresh()

        bSuccess = True
        Return bSuccess
    End Function

    Private Function ReturnDataTable(ByVal Masterdb As DataTable, ByVal BoNum As String) As DataTable
        Dim Dtab As New DataTable

        Dtab.Columns.Add("BoNum")
        Dtab.Columns.Add("Number")
        Dtab.Columns.Add("fSaleOrdeNo")
        Dtab.Columns.Add("PurchaseDate")
        Dtab.Columns.Add("SupplierName")
        Dtab.Columns.Add("DeliveryAddress")
        Dtab.Columns.Add("GoodsName")
        Dtab.Columns.Add("GoodsDescript")
        Dtab.Columns.Add("ReceiveCode")
        Dtab.Columns.Add("ReceiveType")
        Dtab.Columns.Add("DSCTruck")
        Dtab.Columns.Add("DGDelivery")
        Dtab.Columns.Add("CompleteStatus")
        Dtab.Columns.Add("Contents2")
        Dtab.Columns.Add("Remark2")
        Dtab.Columns.Add("fEmployeeName2")
        Dtab.Columns.Add("DGKD")
        Dtab.Columns.Add("PONum")
        Try
            Dim I As Integer = 1
            Masterdb.AcceptChanges()

            For Each Row As DataRow In Masterdb.Rows()
                Dim NRow As DataRow = Dtab.NewRow()
                NRow("BoNum") = BoNum
                NRow("Number") = I
                NRow("fSaleOrdeNo") = Row("fSaleOrdeNo")
                NRow("PurchaseDate") = Row("PurchaseDate")
                If IsDate(Row("PurchaseDate")) = True Then
                    NRow("PurchaseDate") = Format(CType(Row("PurchaseDate"), Date), "yyyy-MM-dd")
                Else
                    NRow("PurchaseDate") = Row("PurchaseDate")
                End If
                NRow("SupplierName") = Row("SupplierName")
                NRow("DeliveryAddress") = Row("DeliveryAddress")
                NRow("GoodsName") = Row("GoodsName")
                NRow("GoodsDescript") = Row("GoodsDescript")
                NRow("ReceiveCode") = Row("ReceiveCode")
                NRow("ReceiveType") = Row("ReceiveType")
                NRow("DSCTruck") = Row("DSCTruck")
                NRow("DGDelivery") = Row("DGDelivery")
                NRow("CompleteStatus") = Row("CompleteStatus")
                NRow("PONum") = Row("PoNum")
                NRow("Contents2") = Row("Contents2")

                NRow("Remark2") = Row("Remark2")
                NRow("fEmployeeName2") = Row("fEmployeeName2")
                NRow("DGKD") = Row("DGKD")
                Dtab.Rows.Add(NRow)
                I += 1
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

        Dtab.AcceptChanges()

        Return Dtab
    End Function

#End Region

#Region " Load TreeView "

    ''' <summary>
    ''' 加載首結點
    ''' </summary>
    ''' <param name="Tvw"></param>
    ''' <param name="title"></param>
    ''' <remarks></remarks>
    Private Sub Load_TreeView(ByRef Tvw As TreeView, ByVal title As String)
        Tvw.Nodes.Clear()
        Dim Node As TreeNode = Tvw.Nodes.Add(title)
        Node.Nodes.Add("...")
        Node.Expand()
        Tvw.SelectedNode = Node
    End Sub

    Private Sub Load_TreeNode(ByVal Node As TreeNode, ByVal Dtab As DataTable)
        Try
            If Node Is Nothing OrElse Node.Nodes.Count < 1 Then Exit Sub
            If Node.Nodes(0).Text.Trim <> "..." Then Exit Sub

            Node.Nodes.Clear()
            Dim Level As Integer = Node.Level

            Dim RowFilter As String = "fLevel=" & Level & "  "

            If Level >= 1 Then
                RowFilter = "fParentCode='" & Node.Tag.ToString() & "'"
            End If

            Dim DRow() As DataRow = Dtab.Select(RowFilter)

            If DRow.Length > 0 Then

                For Each row As DataRow In DRow
                    Dim fCode As String = row("fCode") & ""
                    Dim fName As String = row("fName") & ""
                    Dim tempNode As TreeNode = Node.Nodes.Add(fName)
                    tempNode.Tag = fCode
                    Dim SRow() As DataRow = Dtab.Select("fParentCode='" & fCode & "'")
                    If SRow.Length > 0 Then
                        tempNode.Nodes.Add("...")
                    End If
                Next

            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region " DataGridView "

    Private Sub SetDataGridViewWidth()
        Me.DGV_Master.Columns("BoNum").Width = 80
        Me.DGV_Master.Columns("fLevel1").Width = 40
        Me.DGV_Master.Columns("LastCompleteRemark").Width = 40
        Me.DGV_Master.Columns("LastCallBackTime").Width = 40
        Me.DGV_Master.Columns("ReceiveCallTime").Width = 40
        Me.DGV_Master.Columns("CompleteRemark").Width = 40
        Me.DGV_Master.Columns("CustomerName").Width = 60
        Me.DGV_Master.Columns("ContactPhone").Width = 100
        Me.DGV_Master.Columns("fSaleOrdeNo").Width = 120
        Me.DGV_Master.Columns("FullName").Width = 80
        Me.DGV_Master.Columns("FullName2").Width = 0
        Me.DGV_Master.Columns("Contents").Width = 220
        Me.DGV_Master.Columns("LastCallBackRemark").Width = 220
        Me.DGV_Master.Columns("TakeTime").Width = 60
        Me.DGV_Master.Columns("ReceiveCallDate").Width = 80
        Me.DGV_Master.Columns("ListenPsn").Width = 60
        Me.DGV_Master.Columns("CallBackStatus").Width = 60
        Me.DGV_Master.Columns("LastCallBackDate").Width = 80
        Me.DGV_Master.Columns("LastCallBackPsn").Width = 60
        Me.DGV_Master.Columns("Remark").Width = 80
        Me.DGV_Master.Columns("AgentCode").Width = 60
        Me.DGV_Master.Columns("SupplierName").Width = 60
        Me.DGV_Master.Columns("GoodsName").Width = 80
        Me.DGV_Master.Columns("fEmployeeName").Width = 80
        Me.DGV_Master.Columns("DSCTruck").Width = 60
        Me.DGV_Master.Columns("DGKD").Width = 80
        Me.DGV_Master.Columns("DGDelivery").Width = 80
        Me.DGV_Master.Columns("DeliveryAddress").Width = 80
    End Sub

    Private Sub SetDataGridEnabled(ByVal bEnabled As Boolean)
        Dim bReadOnly As Boolean = Not bEnabled
        Me.TabControl2.SelectedIndex = 1
        Me.DataGridView1.AllowUserToAddRows = bEnabled
        Me.DataGridView1.AllowUserToDeleteRows = bEnabled
        'Me.DataGridView1.AllowUserToResizeRows = bEnabled
        Me.DataGridView1.ReadOnly = bReadOnly
        If bEnabled Then
            Me.DataGridView1.Columns("Number").ReadOnly = True
        End If
    End Sub

    Private Sub SetWidthDataGrid()
        'If Me.DataGridView1.Columns("fSaleOrdeNo").Width < 60 Then
        Me.DataGridView1.Columns("Number").Width = 40
        Me.DataGridView1.Columns("fSaleOrdeNo").Width = 80
        Me.DataGridView1.Columns("Contents2").Width = 150
        Me.DataGridView1.Columns("PurchaseDate").Width = 70
        Me.DataGridView1.Columns("SupplierName").Width = 40
        Me.DataGridView1.Columns("DeliveryAddress").Width = 150
        Me.DataGridView1.Columns("GoodsName").Width = 80
        Me.DataGridView1.Columns("GoodsDescript").Width = 200
        Me.DataGridView1.Columns("DSCTruck").Width = 50
        Me.DataGridView1.Columns("DGDelivery").Width = 100
        Me.DataGridView1.Columns("ReceiveCode").Width = 60
        Me.DataGridView1.Columns("ReceiveType").Width = 80
        Me.DataGridView1.Columns("CompleteStatus").Width = 100
        'End If
    End Sub

#End Region

#End Region

#Region " Event "

#Region " Form Load "

    Private Sub Frm_CSReceiveInformation_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        fLoadBool = False
        Init()

        'Dim T As Thread = New Thread(New ThreadStart(AddressOf ReturnInitDataSet))
        'T.Start()
        'Dim T1 As Thread = New Thread(New ThreadStart(AddressOf InvokeExecFind))
        'T1.Start()
        Me.ReturnInitDataSet()

        Dim whereExp As String = Me.GetWhereExp()
        ExecFind(whereExp)

        Dim whereExp1 As String = Me.GetWhereExp1()
        ExecFind1(whereExp1)

        FillServiceType(dsInfo.Tables(0))
        Me.FillSupplierName(dsInfo.Tables(1).Copy())
        Me.FillEmployee(dsInfo.Tables(2))
        Me.FillDSCTruck(dsInfo.Tables(3))
        Me.Load_TreeView(Me.Tvw_ItemType, "全部")
        SetGridCaptionVisible(Me.DGV_Master, Fields, "Frm_CSReceiveInformation")
        fLoadBool = True
    End Sub

#End Region

#Region " CheckBox Event "

    Private Sub ckb_start_CheckStateChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ckb_start.CheckStateChanged
        Dim chk As CheckBox = DirectCast(sender, CheckBox)
        Me.DateTimePicker1.Enabled = chk.Checked
    End Sub

    Private Sub ckb_End_CheckStateChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ckb_End.CheckStateChanged
        Dim chk As CheckBox = DirectCast(sender, CheckBox)
        Me.DateTimePicker2.Enabled = chk.Checked
    End Sub

    Private Sub CheckBox1_CheckStateChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckStateChanged
        Me.Timer1.Enabled = Me.CheckBox1.Checked
    End Sub

#End Region

#Region " button "

    Private Sub btnFind_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFind.Click
        Dim whereExp As String = Me.GetWhereExp()
        ExecFind(whereExp)
        HistoryTime = Now()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If Me.Tvw_ItemType.Visible = False Then
            Me.Tvw_ItemType.Visible = True
        Else
            Me.Tvw_ItemType.Visible = False
        End If
    End Sub

    ''' <summary>
    ''' 查詢銷售訂單信息
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim frm As Form_SelectSaleInfo
        Try
            frm = New Form_SelectSaleInfo()
            frm.fSaleOrdeNo = Me.txtfSaleOrdeNo.Text.Trim

            If frm.ShowDialog() = DialogResult.OK Then

                If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd OrElse ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                    Dim dgMaster As DataGridView = frm.DGV_Master
                    Dim dgDetail As DataGridView = frm.DGV_Detail

                    If Not dgMaster.CurrentRow Is Nothing Then
                        '' Me.txtfSaleOrdeNo.Text = dgMaster.CurrentRow.Cells("fSaleOrdeNo").Value & ""
                        If dgMaster.CurrentRow.Cells("fLinkMan").Value & "" <> "" Then
                            Me.txtCustomerName.Text = dgMaster.CurrentRow.Cells("fLinkMan").Value & ""
                        End If
                        If dgMaster.CurrentRow.Cells("fLinkPhone").Value & "" <> "" Then
                            Me.txtContactPhone.Text = dgMaster.CurrentRow.Cells("fLinkPhone").Value & ""
                        End If
                        Me.txtPurchaseDate.Text = dgMaster.CurrentRow.Cells("fSaleDate").Value & ""
                        Me.txtDeliveryAddress.Text = dgMaster.CurrentRow.Cells("fDeliverAddress").Value & ""
                        Dim Enname As String = ""
                        Dim SupperItem As String = ""
                        Dim fSaleOrdeNo As String = dgMaster.CurrentRow.Cells("fSaleOrdeNo").Value & ""
                        Dim fRemark As String = ""
                        Dim fDeliverMode As String = dgMaster.CurrentRow.Cells("fDeliverMode").Value & ""

                        If Me.txtfSaleOrdeNo.Text.Trim = "" Then
                            Me.txtfSaleOrdeNo.Text = fSaleOrdeNo
                        End If
                        If Not dgDetail.CurrentRow Is Nothing Then
                            Enname = dgDetail.CurrentRow.Cells("Enname").Value & ""
                            SupperItem = dgDetail.CurrentRow.Cells("SupperItem").Value & ""
                            fRemark = dgDetail.CurrentRow.Cells("fRemark").Value & ""
                            If SupperItem = "" Then
                                SupperItem = dgDetail.Rows(0).Cells("SupperItem").Value & ""
                                fRemark = dgDetail.Rows(0).Cells("fRemark").Value & ""
                            End If
                        ElseIf dgDetail.RowCount > 0 Then
                            Enname = dgDetail.Rows(0).Cells("Enname").Value & ""
                            SupperItem = dgDetail.Rows(0).Cells("SupperItem").Value & ""
                            fRemark = dgDetail.Rows(0).Cells("fRemark").Value & ""
                        End If
                        Me.txtGoodsDescript.Text = fRemark
                        If SupperItem <> "" Then
                            Me.txtGoodsName.Text = SupperItem
                        End If
                        If Enname <> "" Then
                            Me.txtEnName.Text = Enname
                        End If
                        If fDeliverMode = "行送貨" Then
                            If fRemark.IndexOf("(") >= 0 AndAlso fRemark.IndexOf(")") > 0 AndAlso fRemark.IndexOf("(") + 1 < fRemark.IndexOf(")") - 1 Then
                                Me.cbxSupplierName.Text = fRemark.Substring(fRemark.IndexOf("(") + 1, fRemark.IndexOf(")") - (fRemark.IndexOf("(") + 1))
                            End If
                        End If
                    End If
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region "TabControl"

    Private Sub TabControl1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TabControl1.KeyDown

        Select Case e.KeyCode
            Case Keys.S
                If e.Control = True Then
                    If (ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd OrElse ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit) Then
                        MainForm.ToolStripSave.PerformClick()
                    ElseIf (action_help = IDServer.IDServer.ActionBtn.ActionAdd OrElse action_help = IDServer.IDServer.ActionBtn.ActionEdit) Then
                        Me.ToolStripMenuItem_Save_Click(Nothing, Nothing)
                    End If
                End If
        End Select
    End Sub

    Private Sub TabControl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
        If Me.TabControl1.SelectedIndex = 1 Then
            Dim BoNum As String = "ErrorNums"
            If Not Me.DGV_Master.CurrentRow Is Nothing Then
                BoNum = Me.DGV_Master.CurrentRow.Cells("BoNum").Value & ""
            End If
            Me.FillDetail(BoNum)
            If Me.DGV_OldPhone.RowCount > 0 Then
                CType(Me.DGV_OldPhone.DataSource, DataTable).Clear()
            End If
        End If
        Me.lbMessageRefresh.Text = ""
    End Sub

    Private Sub TabControl1_Selecting(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlCancelEventArgs) Handles TabControl1.Selecting
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd OrElse ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit _
            OrElse action_help = IDServer.IDServer.ActionBtn.ActionAdd OrElse action_help = IDServer.IDServer.ActionBtn.ActionEdit Then
            e.Cancel = True
        End If
    End Sub

    'Private Sub TabControl1_VisibleChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabControl1.VisibleChanged
    '    If Me.fLoadBool = False Then Exit Sub

    'End Sub

#End Region

#Region "DataGridView"

    Private Sub DGV_Master_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV_Master.CellDoubleClick
        'Me.TabControl1.SelectedIndex = 1
    End Sub

    Private Sub DGV_Detail_CurrentCellChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGV_Detail.CurrentCellChanged
        If action_help = IDServer.IDServer.ActionBtn.ActionHelp Then
            Dim BoNum As String = ""
            If Not Me.DGV_Detail.CurrentRow Is Nothing Then
                Dim Number = Me.DGV_Detail.CurrentRow.Cells("Number").Value & ""
                Me.FillCallBackDetail(Number)
            End If
        End If
    End Sub

    <System.Diagnostics.DebuggerNonUserCode()> _
    Private Sub DGV_Master_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DGV_Master.RowPostPaint, DGV_OldPhone.RowPostPaint
        Try
            App.DGV_RowPostPaint(sender, e)
        Catch ex As Exception
            MessageBox.Show("DGV_Master_RowPostPaint:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub DataGridView1_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellDoubleClick
        Try
            If Me.DataGridView1.CurrentCell Is Nothing Then Exit Sub

            Select Case e.ColumnIndex
                Case Me.DataGridView1.Columns("fSaleOrdeNo").Index

                    Dim frm As New Form_SelectSaleInfo()
                    frm.fSaleOrdeNo = Me.DataGridView1.CurrentRow.Cells("fSaleOrdeNo").Value & ""
                    If frm.ShowDialog() = DialogResult.OK Then
                        If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then Exit Sub
                        Dim isAdd As Boolean = Me.DataGridView1.CurrentRow.IsNewRow()

                        Dim dgMaster As DataGridView = frm.DGV_Master
                        Dim dgDetail As DataGridView = frm.DGV_Detail
                        If Not dgMaster.CurrentRow Is Nothing Then

                            Dim PurchaseDate As String = dgMaster.CurrentRow.Cells("fSaleDate").Value & ""
                            Dim DeliveryAddress As String = dgMaster.CurrentRow.Cells("fDeliverAddress").Value & ""
                            Dim Enname As String = ""
                            Dim SupperItem As String = ""
                            Dim fSaleOrdeNo As String = dgMaster.CurrentRow.Cells("fSaleOrdeNo").Value & ""
                            Dim fRemark As String = ""
                            Dim fDeliverMode As String = dgMaster.CurrentRow.Cells("fDeliverMode").Value & ""
                            Dim GoodsName As String = ""
                            Dim GoodsDescript As String = ""
                            Dim bImport As Boolean = False

                            For I As Integer = 0 To dgDetail.RowCount - 1
                                If dgDetail.Rows(I).Cells("RowId").Value = True Then
                                    bImport = True
                                    If GoodsName.Trim <> "" Then
                                        GoodsName += "     "
                                    End If
                                    GoodsName += dgDetail.Rows(I).Cells("SupperItem").Value & ""
                                    If GoodsDescript.Trim <> "" Then
                                        GoodsDescript += "   "
                                    End If
                                    GoodsDescript += dgDetail.Rows(I).Cells("fRemark").Value & ""
                                End If
                            Next
                            If bImport = False AndAlso dgDetail.RowCount > 0 Then
                                GoodsName = dgDetail.Rows(0).Cells("SupperItem").Value & ""
                                GoodsDescript = dgDetail.Rows(0).Cells("fRemark").Value & ""
                            End If
                            fRemark = GoodsDescript
                            If fDeliverMode = "行送貨" Then
                                If fRemark.IndexOf("(") >= 0 AndAlso fRemark.IndexOf(")") > 0 AndAlso fRemark.IndexOf("(") + 1 < fRemark.IndexOf(")") - 1 Then
                                    SupperItem = fRemark.Substring(fRemark.IndexOf("(") + 1, fRemark.IndexOf(")") - (fRemark.IndexOf("(") + 1))
                                End If
                            ElseIf fDeliverMode = "送貨" Then
                                SupperItem = "A貨"
                            End If
                            Dim Dd As DataTable = DirectCast(Me.DataGridView1.DataSource, DataTable)
                            Dim row As DataRow = Dd.NewRow()
                            row("PurchaseDate") = PurchaseDate
                            row("SupplierName") = SupperItem
                            row("DeliveryAddress") = DeliveryAddress
                            row("GoodsName") = GoodsName
                            row("GoodsDescript") = GoodsDescript
                            row("fSaleOrdeNo") = fSaleOrdeNo
                            Dd.Rows.Add(row)
                            Dd.AcceptChanges()
                        End If
                    End If

                Case Me.DataGridView1.Columns("ReceiveCode").Index, Me.DataGridView1.Columns("ReceiveType").Index

                    If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then Exit Sub

                    If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd OrElse ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                        If Me.cbxItemParentNo.Text.Trim = "" Then
                            MessageBox.Show("請先選擇來電類別。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Warning)
                            Me.cbxItemParentNo.Focus()
                            SendKeys.Send("{F4}")
                            Exit Sub
                        End If
                    End If

                    Dim frm As New Form_CustomerServerType(True)
                    frm.dt = Me.dsInfo.Tables(0).Copy()
                    Dim fCode As String = ""
                    Dim fCode2 As String = ""
                    If (Me.cbxItemParentNo.Text.Trim <> "" AndAlso Me.cbxItemParentNo.SelectedValue & "" = "11") _
                        AndAlso (Me.cbxCustomerServiceType.Text.Trim <> "" AndAlso Me.cbxCustomerServiceType.SelectedValue & "" = "1101") Then
                        fCode2 = Me.cbxAgentCode.Text
                    Else
                        fCode = Me.cbxItemParentNo.Text
                    End If
                    frm.ItemParentNo = fCode
                    frm.ItemParentNo2 = fCode2

                    If frm.ShowDialog() = DialogResult.OK Then

                        Dim dg As DataGridView = frm.DataGridView1
                        If Not dg.CurrentRow Is Nothing Then
                            Me.DataGridView1.CurrentRow.Cells("ReceiveCode").Value = dg.CurrentRow.Cells("fCode").Value & ""
                            Me.DataGridView1.CurrentRow.Cells("ReceiveType").Value = dg.CurrentRow.Cells("fName").Value & ""
                            Me.DataGridView1.EndEdit()
                            Me.DataGridView1.Update()
                            Me.DataGridView1.Refresh()
                        End If

                    End If
                Case Me.DataGridView1.Columns("DSCTruck").Index
                    If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then Exit Sub
                    Me.cbxDSCTruck1.Visible = True
                    Dim Rect As Rectangle = Me.DataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, False)
                    Dim headwidth As Int32 = Me.DataGridView1.RowHeadersWidth
                    Rect.Y = Rect.Y + Rect.Height - headwidth
                    Me.cbxDSCTruck1.Tag = e
                    Me.cbxDSCTruck1.Bounds = Rect
                    ' Me.cbxDSCTruck1.Parent = Me.DataGridView1
                Case Else

            End Select

        Catch ex As Exception
            MessageBox.Show(ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub DataGridView1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyDown
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd OrElse ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Select Case e.KeyCode
                    Case Keys.Delete
                        If Me.DataGridView1.CurrentCell.IsInEditMode = False AndAlso Me.DataGridView1.CurrentRow.IsNewRow() = False Then
                            If MsgBox(My.resources.ConfirmDelete, MsgBoxStyle.Question + MsgBoxStyle.OkCancel, Msg.CompanyName) = MsgBoxResult.Ok Then
                                Dim DGView As DataGridView = DirectCast(sender, DataGridView)
                                DGView.Rows.RemoveAt(DGView.CurrentRow.Index)
                                DGView.Update()
                            End If
                        End If
                End Select
            End If
        Catch ex As Exception
            MsgBox("DGridView2_KeyDown:" & ex.Message & ex.StackTrace)
        End Try
    End Sub

    <System.Diagnostics.DebuggerNonUserCode()> _
    Private Sub DataGridView1_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DataGridView1.RowPostPaint
        Try
            App.DGV_RowPostPaint(sender, e)
        Catch ex As Exception
            MessageBox.Show("DGV_Master_RowPostPaint:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub DGV_Master_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DGV_Master.DoubleClick
        Me.TabControl1.SelectedIndex = 1
    End Sub


#End Region

#Region "Combobox"

    Private Sub cbxItemParentNo_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbxItemParentNo.SelectedValueChanged
        Try

            If Me.fLoadBool = False Then Exit Sub

            If Me.fillBool = True Then Exit Sub

            Dim RowFilter As String = ""

            If Me.cbxItemParentNo.SelectedValue Is Nothing Then
                RowFilter = "1<>1"
            Else
                If Me.cbxItemParentNo.SelectedValue.ToString.Length < 1 Then
                    RowFilter = "1<>1"
                Else
                    RowFilter = "fParentCode='" & Me.cbxItemParentNo.SelectedValue.ToString() & "'"
                End If
            End If

            Dim dtab As DataTable = Me.dsInfo.Tables(0).Copy()
            Me.fillBool = True
            Dim dv As DataView = dtab.DefaultView
            dv.RowFilter = RowFilter

            Me.cbxCustomerServiceType.DataSource = dv
            Me.cbxCustomerServiceType.DisplayMember = "fName"
            Me.cbxCustomerServiceType.ValueMember = "fCode"

            Me.fillBool = False
            If Me.cbxCustomerServiceType.Items.Count > 1 Then
                Me.cbxCustomerServiceType.Text = ""
                Me.cbxCustomerServiceType.SelectedIndex = -1
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub cbxCustomerServiceType_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbxCustomerServiceType.SelectedValueChanged
        Try
            If Me.fLoadBool = False Then Exit Sub
            If Me.fillBool = True Then Exit Sub

            If TypeOf Me.cbxCustomerServiceType.SelectedValue Is String Then
                Dim fCode As String = Me.cbxCustomerServiceType.SelectedValue & ""
                Dim RowFilter = "1<>1"

                Dim CC As String = fCode.Substring(0, 2)
                '類型(是代理行還是下一層節點)
                Dim isAnger As Boolean = False

                '查找是否有TypeCode信息，如有則取出來
                Dim typecodes As Object
                Dim rows() As DataRow = dsInfo.Tables(0).Select("fCode='" + fCode + "'")
                If rows.Length > 0 Then
                    typecodes = rows(0)("FTypeCodes")
                    If TypeOf typecodes Is System.DBNull OrElse String.IsNullOrEmpty(typecodes.ToString) Then
                        isAnger = False
                    Else
                        isAnger = True
                    End If
                End If

                '填充下一層菜單
                If isAnger = True Then
                    RowFilter = ""
                    Dim types() As String = typecodes.ToString.Split(",")
                    For i As Integer = 0 To types.Length - 1
                        RowFilter += "fTypeCode='" + types(i) + "'"
                        If i < types.Length - 1 Then
                            RowFilter += " or "
                        End If
                    Next
                    Me.FillAgentInformation(Me.dsInfo.Tables(1).Copy, RowFilter)
                Else
                    RowFilter = "fParentCode='" + fCode + "'"
                    FillAgentInformation2(Me.cbxAgentCode, RowFilter)
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    'Private Sub cbxAgentCode_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs)
    '    Try
    '        If Me.fLoadBool = False Then Exit Sub

    '        If Me.fillBool = True Then Exit Sub
    '        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd OrElse ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
    '            If TypeOf Me.cbxAgentCode.SelectedValue Is String AndAlso Me.cbxAgentCode.Text.Trim <> "" Then
    '                Dim AgentCode As String = Me.cbxAgentCode.SelectedValue & ""
    '                Dim DRow() As DataRow = Me.dsInfo.Tables(1).Select("AgentCode='" & AgentCode & "'")
    '                If DRow.Length > 0 Then
    '                    If DRow(0).Item("AgentBrand") & "" <> "" AndAlso RichTextBoxContents.Text.Trim = "" Then
    '                        RichTextBoxContents.Text = DRow(0).Item("AgentBrand") & ""
    '                    End If
    '                End If
    '                If Me.cbxCustomerServiceType.SelectedValue & "" <> "1101" Then
    '                    If Me.cbxSupplierName.FindString(Me.cbxAgentCode.Text.Trim) >= 0 Then
    '                        Me.cbxSupplierName.Text = cbxAgentCode.Text.Trim
    '                    End If
    '                End If
    '            End If
    '        End If

    '        If (TypeOf Me.cbxAgentCode.SelectedValue Is String) AndAlso (Not Me.cbxCustomerServiceType.SelectedValue Is Nothing AndAlso Me.cbxCustomerServiceType.SelectedValue.ToString = "1101") Then
    '            ''填充投訴小類別
    '            Dim AgentCode As String = Me.cbxAgentCode.SelectedValue & ""
    '            Dim RowFilter As String = " fParentCode='" & AgentCode & "'"
    '            FillItemNo2(Me.dsInfo.Tables(0).Copy(), RowFilter)
    '        Else
    '            ''清空來電類別小類
    '            If TypeOf Me.cbxItemNo2.DataSource Is DataView Then
    '                CType(Me.cbxItemNo2.DataSource, DataView).RowFilter = "1<>1"
    '            End If
    '        End If
    '        'ComboBox1.Visible = False
    '    Catch ex As Exception
    '        MessageBox.Show(ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
    '    End Try
    'End Sub

    Private Sub cbxAgentCode_SelectedValueChanged2(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbxAgentCode.SelectedValueChanged
        Try
            Dim cbx As ComboBox = CType(sender, ComboBox)
            If cbx Is Nothing Then
                Exit Sub
            End If
            If TypeOf cbx.SelectedValue Is String And cbx.Focused = True Then
                Dim fCode As String = Me.cbxAgentCode.SelectedValue & ""
                Dim RowFilter = "1<>1"

                Dim CC As String = fCode.Substring(0, 2)
                '類型(是代理行還是下一層節點)
                Dim isAnger As Boolean = False

                '查找是否有TypeCode信息，如有則取出來
                Dim typecodes As Object
                Dim rows() As DataRow = dsInfo.Tables(0).Select("fCode='" + fCode + "'")
                If rows.Length > 0 Then
                    typecodes = rows(0)("FTypeCodes")
                    If TypeOf typecodes Is System.DBNull OrElse String.IsNullOrEmpty(typecodes.ToString) Then
                        isAnger = False
                    Else
                        isAnger = True
                    End If
                End If

                '填充下一層菜單
                If isAnger = True Then
                    RowFilter = ""
                    Dim types() As String = typecodes.ToString.Split(",")
                    For i As Integer = 0 To types.Length - 1
                        RowFilter += "fTypeCode='" + types(i) + "'"
                        If i < types.Length - 1 Then
                            RowFilter += " or "
                        End If
                    Next
                    Me.FillAgentInformation(Me.dsInfo.Tables(1).Copy(), RowFilter)
                Else
                    RowFilter = "fParentCode='" + fCode + "'"
                    FillAgentInformation2(Me.cbxItemNo2, RowFilter)
                End If

                If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
                    If Me.cbxSupplierName.Text.Trim = "" AndAlso ("|002002006|002002008|001002006|001002008|".Contains("|" + fCode + "|")) Then '002002006——公司家私缺貨；002002008——公司電器缺貨
                        Me.cbxSupplierName.Text = "A貨"
                    End If
                    If cbx.Text = "電器(公司送)" Then
                        Me.cbxSupplierName.Text = "電器公司送"
                    Else
                        If Me.cbxSupplierName.Text = "電器公司送" Then
                            Me.cbxSupplierName.Text = ""
                        End If
                    End If
                    If cbx.Text.Trim.Equals("家私(公司送)", StringComparison.InvariantCultureIgnoreCase) Then
                        Me.cbxSupplierName.Text = "A貨"
                    End If
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub cbxItemNo2_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbxItemNo2.SelectedValueChanged
        If Me.fLoadBool = False Then Exit Sub
        If Me.fillBool = True Then Exit Sub
        Dim cbx As ComboBox = CType(sender, ComboBox)
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd OrElse ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
            If TypeOf cbx.SelectedValue Is String AndAlso cbx.Text.Trim <> "" Then
                Dim AgentCode As String = cbx.SelectedValue & ""
                Dim DRow() As DataRow = Me.dsInfo.Tables(1).Select("AgentCode='" & AgentCode & "'")
                If DRow.Length > 0 Then
                    If DRow(0).Item("AgentBrand") & "" <> "" AndAlso RichTextBoxContents.Text.Trim = "" Then
                        RichTextBoxContents.Text = DRow(0).Item("AgentBrand") & ""
                    End If
                End If
                If Me.cbxItemParentNo.SelectedValue & "" <> "002" Then
                    If Me.cbxSupplierName.FindString(cbx.Text.Trim) >= 0 Then
                        Me.cbxSupplierName.Text = cbx.Text.Trim
                    End If
                End If
            End If
        End If

    End Sub

#End Region

#Region "ContextMenuStrip1"

    Private Sub ContextMenuStrip1_Opening(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStrip1.Opening

        Dim bEnabled As Boolean = Not (Me.DGV_Master.CurrentRow Is Nothing)

        If Me.TabControl1.SelectedIndex = 0 Then
            Me.ToolStripMenuItem_CallBackEdit.Enabled = False
            Me.ToolStripMenuItem_CallBackDelet.Enabled = False
            Me.ToolStripMenuItem_Save.Enabled = False
            Me.ToolStripMenuItem_Cancel.Enabled = False
            Me.ToolStripMenuItem_CallBackAdd.Enabled = bEnabled AndAlso (action_help = IDServer.IDServer.ActionBtn.ActionHelp) AndAlso (ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp)
        Else

            Dim bb As Boolean = False
            If Not Me.DGV_Detail.CurrentRow Is Nothing Then
                bb = True
            End If
            Me.ToolStripMenuItem_CallBackAdd.Enabled = bEnabled AndAlso (action_help = IDServer.IDServer.ActionBtn.ActionHelp) AndAlso (ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp)
            Me.ToolStripMenuItem_CallBackEdit.Enabled = bEnabled AndAlso bb AndAlso (action_help = IDServer.IDServer.ActionBtn.ActionHelp) AndAlso (ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp)
            Me.ToolStripMenuItem_CallBackDelet.Enabled = bEnabled AndAlso bb AndAlso (action_help = IDServer.IDServer.ActionBtn.ActionHelp) AndAlso (ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp)

            Me.ToolStripMenuItem_Cancel.Enabled = (action_help = IDServer.IDServer.ActionBtn.ActionAdd) OrElse (action_help = IDServer.IDServer.ActionBtn.ActionEdit) AndAlso (ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp)
            Me.ToolStripMenuItem_Save.Enabled = (action_help = IDServer.IDServer.ActionBtn.ActionAdd) OrElse (action_help = IDServer.IDServer.ActionBtn.ActionEdit) AndAlso (ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp)

        End If
    End Sub

    Private Sub ToolStripMenuItem_CallBackAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem_CallBackAdd.Click
        Try
            If Me.TabControl1.SelectedIndex = 0 Then
                Me.TabControl1.SelectedIndex = 1
            End If
            Me.action_help = IDServer.IDServer.ActionBtn.ActionAdd
            FillCallBackDetail("NoCode")
            Me.SetEnabled_BackCall(True)
            Me.txtCallBackPsn2.Text = PubUserCode
            Dim startDate As Object = Exec("select Convert(varchar(19),Getdate(),21)", E_ExecType.ExecuteScalar)
            Me.txtCallBackTime.Text = Format(CDate(startDate), "HH:mm")
            If Not Me.DGV_Master.CurrentRow Is Nothing Then
                Dim LastCompleteRemark As String = Me.DGV_Master.CurrentRow.Cells("LastCompleteRemark").Value & ""
                If LastCompleteRemark.ToLower().IndexOf("ok") >= 0 Then
                    Me.txtCompleteRemark2.Text = LastCompleteRemark
                End If
            End If
            Me.RichTextBoxfRemark2.Focus()
            If Me.TabControl2.SelectedIndex = 1 Then
                Me.TabControl2.SelectedIndex = 0
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message + ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub ToolStripMenuItem_CallBackEdit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem_CallBackEdit.Click
        Try
            Me.action_help = IDServer.IDServer.ActionBtn.ActionEdit
            Me.SetEnabled_BackCall(True)
            Me.RichTextBoxfRemark2.Focus()
        Catch ex As Exception
            MessageBox.Show(ex.Message + ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub ToolStripMenuItem_CallBackDelet_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem_CallBackDelet.Click
        Try
            If Me.DGV_Detail.CurrentRow Is Nothing Then Exit Sub

            If MessageBox.Show(My.resources.ConfirmDelete, Msg.CompanyName, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
                Dim BoNum As String = Me.txtBoNum.Text.Trim
                Dim Number As String = Me.DGV_Detail.CurrentRow.Cells("Number").Value

                Dim sql As String = " "

                sql &= " Delete CS_CallBackInformation where  BoNum='" & BoNum & "' and Number='" & Number & "'" & vbCrLf
                sql &= " select Top 1 * into[#aa]  from CS_CallBackInformation where BoNum='" & BoNum & "' order by Number desc" & vbCrLf
                sql &= " Update CS_ReceiveInformation  set " & vbCrLf
                sql &= " CallBackStatus=(select count(*) from #aa)," & vbCrLf
                sql &= " LastCallBackTime=b.CallBackTime," & vbCrLf
                sql &= " LastCallBackDate=Convert(varchar(10),b.CallBackDate,21)," & vbCrLf
                sql &= " LastCallBackPsn=b.CallBackPsn," & vbCrLf
                sql &= "LastCompleteRemark=b.CompleteRemark," & vbCrLf
                sql &= "LastCallBackRemark=b.fRemark," & vbCrLf
                sql &= "CompleteStatus = b.CompleteStatus" & vbCrLf
                sql &= " from CS_ReceiveInformation a left join #aa b on a.BoNum=b.BoNum" & vbCrLf
                sql &= " where a.BoNum='" & BoNum & "'" & vbCrLf
                sql &= " select * from [#aa] " & vbCrLf
                sql &= " Drop Table [#aa] " & vbCrLf

                Dim Dtab As New DataTable()

                Dtab = Exec(sql, E_ExecType.DataTable)

                Dim detail As DataTable = DirectCast(Me.DGV_Detail.DataSource, DataTable)

                Dim DRow() As DataRow = detail.Select("Number='" & Number & "'")

                If DRow.Length > 0 Then
                    DRow(0).Delete()
                End If

                detail.AcceptChanges()

                Dim CallBackStatus As Int32 = 0
                Dim CallBackTime As String = ""
                Dim CallBackDate As String = ""
                Dim CallBackPsn As String = ""
                Dim CompleteStatus As Integer = 0

                Dim LastCallBackRemark As String = ""

                Dim LastCompleteRemark As String = ""

                If Dtab.Rows.Count > 0 Then
                    CallBackStatus = 1
                    CallBackTime = Dtab.Rows(0).Item("CallBackTime") & ""
                    CallBackDate = Dtab.Rows(0).Item("CallBackDate")
                    CallBackPsn = Dtab.Rows(0).Item("CallBackPsn") & ""
                    CompleteStatus = Val(Dtab.Rows(0).Item("CompleteStatus") & "")
                    LastCallBackRemark = Dtab.Rows(0).Item("fRemark") & ""
                    LastCompleteRemark = Dtab.Rows(0).Item("CompleteRemark") & ""

                End If

                Dim master As DataTable = DirectCast(Me.DGV_Master.DataSource, DataTable)

                Dim SRow() As DataRow = master.Select("BoNum='" & BoNum & "'")
                If SRow.Length > 0 Then

                    SRow(0).Item("CallBackStatus") = CallBackStatus
                    SRow(0).Item("LastCallBackTime") = CallBackTime
                    SRow(0).Item("LastCallBackDate") = CallBackDate
                    SRow(0).Item("LastCallBackPsn") = CallBackPsn
                    SRow(0).Item("CompleteStatus") = CompleteStatus
                    SRow(0).Item("LastCallBackRemark") = LastCallBackRemark
                    SRow(0).Item("LastCompleteRemark") = LastCompleteRemark
                End If

                Me.DGV_Master.Update()
                Me.DGV_Master.Refresh()

                Me.DGV_Detail.Update()
                Me.DGV_Detail.Refresh()

                If Me.DGV_Detail.RowCount > 0 Then
                    Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(0).Cells("Number")
                Else
                    Me.FillCallBackDetail("")
                End If

                MessageBox.Show("刪除成功。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)

            End If
        Catch ex As Exception
            MessageBox.Show("刪除失敗。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub ToolStripMenuItem_Save_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem_Save.Click
        SaveCallBackData()
    End Sub

    Private Sub ToolStripMenuItem_Cancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem_Cancel.Click
        Try
            Me.action_help = IDServer.IDServer.ActionBtn.ActionHelp
            Me.SetEnabled_BackCall(False)
            Dim Number As String = ""
            If Not Me.DGV_Detail.CurrentRow Is Nothing Then
                Number = Me.DGV_Detail.CurrentRow.Cells("Number").Value & ""
            End If
            Me.FillCallBackDetail(Number)
        Catch ex As Exception
            MessageBox.Show(ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub ToolStripMenuItem_AgentInfo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem_AgentInfo.Click
        Dim frm As Form_AgentInfo = Form_AgentInfo.CreateInstance()
        frm.Show()
    End Sub

    Private Sub ToolStripMenuItem_ShopAddress_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem_ShopAddress.Click
        Dim frm As Form_ShopInfo = Form_ShopInfo.CreateInstance()
        frm.Show()
    End Sub

    Private Sub ToolStripMenuItem_WXInfo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem_WXInfo.Click
        Dim frm As Form_WXInfo = Form_WXInfo.CreateInstance
        frm.Show()
    End Sub

    Private Sub ToolStripMenuItem_ACDeliver_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem_ACDeliver.Click
        Dim frm As Form_ACDelivery = Form_ACDelivery.CreateInstance()
        frm.Show()
    End Sub


#End Region

#Region "TreeView"

    Private Sub Tvw_ItemType_BeforeSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles Tvw_ItemType.BeforeSelect
        If Not Me.Tvw_ItemType.SelectedNode Is Nothing Then
            Me.Tvw_ItemType.SelectedNode.ForeColor = Color.Black
        End If
        e.Node.ForeColor = Color.Blue
    End Sub

    Private Sub Tvw_ItemType_AfterSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles Tvw_ItemType.AfterSelect
        Try
            Me.txt_ItemType.Text = Me.Tvw_ItemType.SelectedNode.Text.Trim
            Me.txt_ItemType.Tag = Me.Tvw_ItemType.SelectedNode.Tag
            Me.Tvw_ItemType.Visible = False
        Catch ex As Exception
            MessageBox.Show(ex.Message + ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub Tvw_ItemType_BeforeExpand(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles Tvw_ItemType.BeforeExpand
        Try
            Me.Load_TreeNode(e.Node, Me.dsInfo.Tables(0))
        Catch ex As Exception
            MessageBox.Show(ex.Message + ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region "Timer1"

    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If Me.TabControl1.SelectedIndex = 0 AndAlso Me.CheckBox1.Checked = True AndAlso Microsoft.VisualBasic.DateDiff(DateInterval.Minute, Me.HistoryTime, Now()) > 1 Then
            If Me.ckb_start.Checked = True AndAlso Me.ckb_End.Checked = True Then
                Dim whereExp As String = Me.GetWhereExp()
                Me.ExecFind(whereExp)
                Label38.Text = Val(Me.Label38.Text) + 1
            End If
        End If
        GC.Collect()
    End Sub

#End Region

#Region "TextBox"

    Private Sub RichTextBoxContents_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RichTextBoxContents.DoubleClick

        If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then Exit Sub
        Try
            Dim bSuccess As Boolean = False
            Dim ItemParentNo As String = ""
            Dim ItemNo As String = ""
            Dim ItemNo2 As String = String.Empty
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd OrElse ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                ItemParentNo = Me.cbxItemParentNo.Text.Trim
                ItemNo = Me.cbxCustomerServiceType.Text.Trim
                ItemNo2 = Me.cbxAgentCode.Text.Trim
                bSuccess = True
            End If

            If bSuccess = True Then
                Dim frm As New Frm_CSComplaintRemarkNew()
                frm.ItemParentNo = ItemParentNo
                frm.ItemNo = ItemNo
                frm.ItemNo2 = ItemNo2
                frm.dt = Me.dsInfo.Tables(0).Copy()
                If frm.ShowDialog() = DialogResult.OK Then
                    Dim fLevel As Integer = frm.fLevel
                    Dim dg As DataGridView
                    If fLevel = 1 Then
                        dg = frm.DataGridView1
                    Else
                        If Not frm.DataGridView2.CurrentRow Is Nothing Then
                            dg = frm.DataGridView2
                        Else
                            dg = frm.DataGridView1
                        End If
                    End If
                    If Not dg.CurrentRow Is Nothing Then
                        Me.RichTextBoxContents.AppendText(dg.CurrentRow.Cells("Remark").Value & vbCrLf)
                    End If
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK)
        End Try
    End Sub

    Private Sub RichTextBoxfRemark2_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RichTextBoxfRemark2.DoubleClick
        If Me.action_help = IDServer.IDServer.ActionBtn.ActionHelp Then Exit Sub
        Try
            Dim bSuccess As Boolean = False

            If action_help = IDServer.IDServer.ActionBtn.ActionAdd OrElse action_help = IDServer.IDServer.ActionBtn.ActionEdit Then
                If Me.cbxCustomerServiceType.Text.Trim = "投訴" AndAlso "|001005|002005|".Contains("|" + Me.cbxCustomerServiceType.SelectedValue.ToString + "|") Then
                    bSuccess = True
                End If

                If bSuccess = True Then
                    Dim frm As New Frm_CSComplaintRemark()
                    If frm.ShowDialog() = DialogResult.OK Then
                        Dim fLevel As Integer = frm.fLevel
                        Dim dg As DataGridView

                        dg = frm.DataGridView2
                        If Not dg.CurrentRow Is Nothing Then
                            Me.RichTextBoxfRemark2.AppendText(dg.CurrentRow.Cells("Remark").Value & vbCrLf)
                        End If

                    End If
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK)
        End Try
    End Sub

#End Region

    Private Sub txtCompleteRemark_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtCompleteRemark.SelectedIndexChanged

    End Sub

#End Region

#Region " Interface "


    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd
        Try
            If AddEnable = False Then
                MessageBox.Show("您没有新增权限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If
            If action_help <> IDServer.IDServer.ActionBtn.ActionHelp Then
                SelectObject.ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
                Return False
            End If
            If Me.TabControl1.SelectedIndex = 0 Then
                Me.TabControl1.SelectedIndex = 1
            End If


            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd OrElse ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                ''已經是新增狀態再按新增則無效
                Return True
            End If

            ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd

            Me.FillDetail("")
            Me.TabControl2.SelectedIndex = 1
            If TypeOf Me.cbxCustomerServiceType.DataSource Is DataView Then
                CType(Me.cbxCustomerServiceType.DataSource, DataView).RowFilter = "1<>1"
            End If
            If TypeOf Me.cbxAgentCode.DataSource Is DataView Then
                CType(Me.cbxAgentCode.DataSource, DataView).RowFilter = "1<>1"
            End If
            If TypeOf Me.cbxItemNo2.DataSource Is DataView Then
                CType(Me.cbxItemNo2.DataSource, DataView).RowFilter = "1<>1"
            End If

            SetButton(ButtonType.Add, False)
            Me.SetEnabled_Receive(True)
            Me.txtListenPsn.Text = PubUserCode
            Me.lbOperatorPsn.Text = PubUserName
            Me.lbOperatorDate.Text = ServerDate
            Dim startDate As Object = Exec("select Convert(varchar(19),Getdate(),21)", E_ExecType.ExecuteScalar)
            SetDataGridEnabled(True)
            Dim Dtab As DataTable = DirectCast(Me.DataGridView1.DataSource, DataTable)
            Dim row As DataRow = Dtab.NewRow()
            Dtab.Rows.Add(row)
            Dtab.AcceptChanges()
            'SetWidthDataGrid()
            Me.txtReceiveCallTime.Text = Format(CDate(startDate), "HH:mm")
            Me.txtCustomerName.Focus()
            Return True
        Catch ex As Exception
            MessageBox.Show(ex.Message + ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel
        Try
            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            Dim BoNum As String = ""
            Dim IsFind As Boolean = False
            If Not Me.DGV_Master.CurrentRow Is Nothing Then
                IsFind = True
                BoNum = Me.DGV_Master.CurrentRow.Cells("BoNum").Value & ""
            End If
            If TypeOf Me.cbxCustomerServiceType.DataSource Is DataView Then
                CType(Me.cbxCustomerServiceType.DataSource, DataView).RowFilter = "1=1"
            End If
            If TypeOf Me.cbxAgentCode.DataSource Is DataView Then
                CType(Me.cbxAgentCode.DataSource, DataView).RowFilter = "1=1"
            End If
            If TypeOf Me.cbxItemNo2.DataSource Is DataView Then
                CType(Me.cbxItemNo2.DataSource, DataView).RowFilter = "1=1"
            End If

            SetButton(ButtonType.Browse, IsFind)
            Me.FillDetail(BoNum)
            Me.SetEnabled_Receive(False)
            SetDataGridEnabled(False)
            If Me.DGV_OldPhone.RowCount > 0 Then
                CType(Me.DGV_OldPhone.DataSource, DataTable).Clear()
            End If
            'Me.DGV_OldPhone.DataSource = ""
            Return True
        Catch ex As Exception
            MessageBox.Show(ex.Message + ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete
        If DeleteEnable = False Then
            MessageBox.Show("没有权限删除", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd OrElse ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit OrElse _
        action_help = IDServer.IDServer.ActionBtn.ActionAdd OrElse action_help = IDServer.IDServer.ActionBtn.ActionEdit Then Return True

        Try
            If Me.DGV_Master.CurrentRow Is Nothing Then Return False

            If MessageBox.Show(My.resources.ConfirmDelete, Msg.CompanyName, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) <> DialogResult.OK Then Return False


            Dim obj As Object
            Dim BoNum As String = Me.DGV_Master.CurrentRow.Cells("BoNum").Value & ""

            Dim sql As String = " select Count(*) from CS_CallBackInformation where BoNum='" & BoNum & "'"

            obj = Exec(sql, E_ExecType.ExecuteScalar) & ""

            If Val(obj) > 0 Then
                MessageBox.Show("已有回複記錄不能刪除。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Return True
            End If

            sql = "      Delete CS_ReceiveInformation where BoNum='" & BoNum & "' " & vbCrLf
            sql &= "   Delete CS_ReceiveSaleInfo where Isnull(BoNum,'')='" & BoNum & "'  " & vbCrLf
            Exec(sql, E_ExecType.ExecuteNonQuery)

            Dim Dtab As DataTable = DirectCast(Me.DGV_Master.DataSource, DataTable)

            Dim DRow() As DataRow = Dtab.Select("BoNum='" & BoNum & "'")

            If DRow.Length > 0 Then
                DRow(0).Delete()
            End If

            Dtab.AcceptChanges()
            Me.DGV_Master.Refresh()
            Dim IsFind As Boolean = False
            If Me.DGV_Master.RowCount > 0 Then
                Me.DGV_Master.CurrentCell = Me.DGV_Master.Rows(Me.DGV_Master.RowCount - 1).Cells("LastCallBackTime")
                BoNum = Me.DGV_Master.Rows(0).Cells("BoNum").Value & ""
                IsFind = True
            Else
                BoNum = ""
            End If
            If Me.TabControl1.SelectedIndex = 1 Then
                Me.FillDetail(BoNum)
            End If
            Me.SetButton(ButtonType.Browse, IsFind)
        Catch ex As Exception
            MessageBox.Show(My.resources.ErrDelete, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit
        If EditEnable = False Then
            MessageBox.Show("您没有权限修改", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If
        If action_help <> IDServer.IDServer.ActionBtn.ActionHelp Then
            SelectObject.ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            Return False
        End If
        Try
            If Me.TabControl1.SelectedIndex = 0 Then
                Me.TabControl1.SelectedIndex = 1
            End If
            ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit
            Me.TabControl2.SelectedIndex = 1
            SetButton(ButtonType.Edit, False)
            Me.SetEnabled_Receive(True)
            Me.lbUpdatePsn.Text = PubUserName
            Me.lbUpdateDate.Text = ServerDate
            SetDataGridEnabled(True)
            Dim Dtab As DataTable = DirectCast(Me.DataGridView1.DataSource, DataTable)
            Dim row As DataRow = Dtab.NewRow()
            Dtab.Rows.Add(row)
            Dtab.AcceptChanges()
            'SetWidthDataGrid()
            Me.RichTextBoxContents.Focus()
            Return True
        Catch ex As Exception
            MessageBox.Show(ex.Message + ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport
        'ExportToExcel(Me.DGV_Master, Msg.CompanyName, "", "")
        Me.Cursor = Cursors.WaitCursor
        Dim Grid As DataGridView = Me.DGV_Master
        Dim ds As New DataSet
        Dim Dtab As DataTable
        Dtab = DirectCast(Grid.DataSource, DataTable).Copy
        Dtab.TableName = "Receive"
        RemoveHideColumn(Grid, Dtab)
        ds.Tables.Add(Dtab)
        'SaveXls(ds)
        Dim frmsavefile As New SaveFileDialog()
        frmsavefile.AddExtension = True
        frmsavefile.Filter = "Microsoft Office Excel 活頁簿（*.xls）|"
        frmsavefile.CheckPathExists = True
        frmsavefile.DefaultExt = ".xls"
        frmsavefile.OverwritePrompt = True
        frmsavefile.Title = "保存文件"
        Dim filename As String = String.Empty
        If frmsavefile.ShowDialog() = DialogResult.OK Then
            filename = frmsavefile.FileName
            If System.IO.File.Exists(filename) Then System.IO.File.Delete(filename)
            saveXlsOle(Dtab, filename)
            If System.IO.File.Exists(filename) Then
                If MessageBox.Show("文件:" + vbNewLine + filename + vbNewLine + "保存成功,是否要打开文件", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
                    System.Diagnostics.Process.Start(filename)
                End If
            End If
        End If
        Me.Cursor = Cursors.Default
    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter
        Try
            Dim Frm_Filter As New Frm_Filter
            Me.Cursor = Cursors.WaitCursor
            Frm_Filter.LoadHeaderCaption(Fields, "Frm_CSReceiveInformation")
            Frm_Filter.ShowDialog()
            Me.Cursor = Cursors.Default
            ReBindGridCaption(Me.DGV_Master, "Frm_CSReceiveInformation")
        Catch ex As Exception
            MsgBox("ActionFilter:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave
        If Validated1() = False Then
            Return False
        End If
        Dim bSuccess As Boolean = SaveReceiveData()
        Return bSuccess
    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function

#End Region

    Private Sub txtfSaleOrdeNo_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtfSaleOrdeNo.KeyDown, txtContactPhone.KeyDown

        Try
            ' If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
            If e.KeyCode = Keys.Enter Then
                Dim whereExp1 As String = Me.GetWhereExp1()
                ExecFind1(whereExp1)
                HistoryTime = Now()
                Me.TabControl2.SelectedIndex = 2
            End If
            ' End If

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Function GetWhereExp1()
        Dim sql As String = ""

        If Me.fLoadBool = False Then
            sql = "  where    1<>1" + vbNewLine
        Else
            If Me.txtfSaleOrdeNo.Text = "" And Me.txtContactPhone.Text = "" Then
                sql = "  where    1<>1" + vbNewLine
            Else
                sql = "   where 1=1 " + vbNewLine
            End If
            If Me.txtfSaleOrdeNo.Text.Trim <> "" Then
                sql &= "  and fSaleOrdeNo like '%" & Me.txtfSaleOrdeNo.Text.Trim & "%'" + vbNewLine
            End If
            If Me.txtContactPhone.Text.Trim <> "" Then
                sql &= "  and ContactPhone like '%" & Me.txtContactPhone.Text.Trim & "%'" + vbNewLine
            End If
        End If
        Return sql
    End Function

    Private Function GetWhereExp2() As String
        Dim whereExp As String = String.Empty
        If Me.fLoadBool = False Then
            whereExp = " where 1<>1 " + vbNewLine
        Else
            whereExp = " where 1=1  --and isnull(ReceiveCode,'')<>''" + vbNewLine
            If Me.txtfSaleOrdeNo.Text.Trim <> "" Then
                whereExp += " and a.fSaleOrdeNo like '%" + Me.txtfSaleOrdeNo.Text.Trim + "%'" + vbNewLine
            End If
            If Me.txtContactPhone.Text.Trim <> "" Then
                whereExp += "  and ( b.ContactPhone like '%" + Me.txtContactPhone.Text.Trim + "%')" + vbNewLine
            End If
        End If
        Return whereExp
    End Function

    Private Sub ExecFind1(ByVal whereExp As String, Optional ByVal bRefresh As Boolean = False)

        'Me.Cursor = Cursors.WaitCursor
        '這個SQL語句是 歷史來電記錄查詢
        Dim sql As String = String.Empty
        Dim temptable As String = "[#" + System.Guid.NewGuid.ToString + "]"
        '查詢新版本的記錄
        sql &= " select   fLevel1,ReceiveCallDate,ReceiveCallTime,FullName=(Isnull(c.fName,'') + '/' + Isnull(b.fName,'')),fSaleOrdeNo,"
        sql &= "         Contents,ListenPsn,CompleteRemark,LastCallBackRemark,Remark,CustomerName,ContactPhone,PurchaseDate,GoodsName,"
        sql &= "         GoodsDescript,DeliveryAddress,"
        sql &= "    BoNum,LastCompleteRemark,LastCallBackTime,a.ItemParentNo,c.fName as ItemParentName,ItemNo,b.fName as ItemName,"
        sql &= "   CompleteStatus=Convert(bit,isnull(CompleteStatus,0)),TakeTime,AgentCode,ItemParentNo2,e.fName as ItemParentNo2Name ,ItemNo2,d.fName as ItemNo2Name,Case when Isnull(ItemNo,'')='1101' then Isnull(b.fName,'')+'/'+Isnull(e.fName,'')+'/'+Isnull(d.fName,'') else '' end  as FullName2,"
        sql &= "   CallBackStatus=Convert(Bit,CallBackStatus), LastCallBackDate, LastCallBackPsn,"
        sql &= "   ComplainLevel,SupplierName,EnName,fEmployeeName,DSCTruck,DGKD,DGDelivery,BillStatus, fOperatorPsn, fOperatorDate = Convert(varchar(10), fOperatorDate, 21), fUpdatePsn, fUpdateDate = Convert(varchar(10), fUpdateDate, 21)"
        sql &= " into " + temptable + "  from CS_ReceiveInformation   a " & vbCrLf
        sql &= " inner join CS_CusterServiceTypes c on a.ItemParentNo=c.fCode left join CS_CusterServiceTypes b on a.ItemNo=b.fCode     "
        sql &= "  left join CS_CusterServiceTypes d on a.ItemNo2=d.fCode left join CS_CusterServiceTypes e on a.ItemParentNo2=e.fCode    " & whereExp + vbNewLine
        sql += IIf(IsDate(Me.NewVersionDateAfter), " and a.ReceiveCallDate>'" + Me.NewVersionDateAfter + "'", "") + vbNewLine

        'sql &= " union all " + vbNewLine + vbNewLine
        '查詢新版本中網格的記錄（有待測試，看數據是否準確）
        sql += "insert into " + temptable + vbNewLine
        sql += " select flevel1 ='',ReceiveCallDate,ReceiveCallTime,FullName=dbo.[f_CSTypesFullName](fCode)," + vbNewLine
        sql += "a.fSaleOrdeNo, Contents=a.Contents2,b.ListenPsn,b.CompleteRemark,b.LastCallBackRemark,a.Remark2,CustomerName," + vbNewLine
        sql += "ContactPhone,a.PurchaseDate,a.GoodsName,a.GoodsDescript,a.DeliveryAddress,a.BoNum,b.LastCompleteRemark" + vbNewLine
        sql += ",b.LastCallBackTime,ItemParentNo='',c.fName as ItemParentName,ItemNo,c.fName as ItemName," + vbNewLine
        sql += "CompleteStatus=Convert(bit,isnull(b.CompleteStatus,0)),TakeTime,AgentCode,ItemParentNo2,ItemParentNo2Name=''" + vbNewLine
        sql += ",ItemNo2,ItemNo2Name='',FullName2='',CallBackStatus=Convert(Bit,CallBackStatus), LastCallBackDate," + vbNewLine
        sql += "LastCallBackPsn,ComplainLevel,a.SupplierName,EnName,fEmployeeName,case when isnull(b.DSCTruck,'')='' then a.DSCTruck else b.DSCTruck end as DSCTruck" + vbNewLine
        sql += ",case when isnull(a.DGKD,'')='' then b.DGKD  else a.DGKD end as DGKD,case when isnull(b.DGDelivery,'')='' then a.DGDelivery else b.DGDelivery end as DGDelivery," + vbNewLine
        sql += "BillStatus, fOperatorPsn,fOperatorDate = Convert(varchar(10), fOperatorDate, 21), fUpdatePsn," + vbNewLine
        sql += "fUpdateDate = Convert(varchar(10), fUpdateDate, 21) from CS_ReceiveSaleInfo a" + vbNewLine
        sql += "inner join CS_ReceiveInformation b On a.Bonum=b.Bonum" + vbNewLine
        sql += "inner join dbo.CS_CusterServiceTypes c on fCode=isnull(ReceiveCode,'')" + vbNewLine
        sql += GetWhereExp2() + vbNewLine
        sql += IIf(IsDate(Me.NewVersionDateAfter), " and b.ReceiveCallDate>'" + Me.NewVersionDateAfter + "'", "") + vbNewLine
        'sql += " union all" + vbNewLine + vbNewLine
        '查詢老版本的記錄
        sql += "insert into " + temptable + vbNewLine
        sql &= " select   fLevel1,ReceiveCallDate,ReceiveCallTime,FullName=(Isnull(c.fName,'') + '/' + Isnull(b.fName,'')),fSaleOrdeNo,"
        sql &= "         Contents,ListenPsn,CompleteRemark,LastCallBackRemark,Remark,CustomerName,ContactPhone,PurchaseDate,GoodsName,"
        sql &= "         GoodsDescript,DeliveryAddress,"
        sql &= "    BoNum,LastCompleteRemark,LastCallBackTime,a.ItemParentNo,c.fName as ItemParentName,ItemNo,b.fName as ItemName,"
        sql &= "   CompleteStatus=Convert(bit,isnull(CompleteStatus,0)),TakeTime,AgentCode,ItemParentNo2,e.fName as ItemParentNo2Name ,ItemNo2,d.fName as ItemNo2Name,Case when Isnull(ItemNo,'')='1101' then Isnull(b.fName,'')+'/'+Isnull(e.fName,'')+'/'+Isnull(d.fName,'') else '' end  as FullName2,"
        sql &= "   CallBackStatus=Convert(Bit,CallBackStatus), LastCallBackDate, LastCallBackPsn,"
        sql &= "   ComplainLevel,SupplierName,EnName,fEmployeeName,DSCTruck,DGKD,DGDelivery,BillStatus, fOperatorPsn, fOperatorDate = Convert(varchar(10), fOperatorDate, 21), fUpdatePsn, fUpdateDate = Convert(varchar(10), fUpdateDate, 21)"
        sql &= "  from CS_ReceiveInformation   a " & vbCrLf
        sql &= "  inner join CS_CusterServiceType c on a.ItemParentNo=c.fCode left join CS_CusterServiceType b on a.ItemNo=b.fCode    "
        sql &= "  left join CS_CusterServiceType d on a.ItemNo2=d.fCode left join CS_CusterServiceType e on a.ItemParentNo2=e.fCode    " & whereExp + vbNewLine
        sql += IIf(IsDate(Me.OldVersionDateBefore), " and a.ReceiveCallDate<'" + Me.OldVersionDateBefore + "'", "") + vbNewLine

        '查詢老版本網格中的記錄
        sql += "insert into " + temptable + vbNewLine
        'sql += " union all " + vbNewLine
        sql += "select flevel1 ='',ReceiveCallDate,ReceiveCallTime,FullName=''," + vbNewLine
        sql += "a.fSaleOrdeNo, Contents=a.Contents2,b.ListenPsn,b.CompleteRemark,b.LastCallBackRemark,a.Remark2,CustomerName," + vbNewLine
        sql += "ContactPhone,a.PurchaseDate,a.GoodsName,a.GoodsDescript,a.DeliveryAddress,a.BoNum,b.LastCompleteRemark" + vbNewLine
        sql += ",b.LastCallBackTime,ItemParentNo='',ItemParentName=''  ,ItemNo,ItemName=''," + vbNewLine
        sql += "CompleteStatus=Convert(bit,isnull(b.CompleteStatus,0))" + vbNewLine
        sql += ",TakeTime,AgentCode,ItemParentNo2,ItemParentNo2Name=''" + vbNewLine
        sql += ",ItemNo2,ItemNo2Name='',FullName2='',CallBackStatus=Convert(Bit,CallBackStatus), LastCallBackDate," + vbNewLine
        sql += "LastCallBackPsn,ComplainLevel,a.SupplierName,EnName,fEmployeeName,case when isnull(b.DSCTruck,'')='' then a.DSCTruck else b.DSCTruck end as DSCTruck" + vbNewLine
        sql += ",case when isnull(a.DGKD,'')='' then b.DGKD  else a.DGKD end as DGKD,case when isnull(b.DGDelivery,'')='' then a.DGDelivery else b.DGDelivery end as DGDelivery," + vbNewLine
        sql += "BillStatus, fOperatorPsn,fOperatorDate = Convert(varchar(10), fOperatorDate, 21), fUpdatePsn," + vbNewLine
        sql += "fUpdateDate = Convert(varchar(10), fUpdateDate, 21) from CS_ReceiveSaleInfo a" + vbNewLine
        sql += "inner join CS_ReceiveInformation b On a.Bonum=b.Bonum" + vbNewLine
        sql += GetWhereExp2() + " and not exists(select * from  dbo.CS_CusterServiceTypes  where fCode=isnull(ReceiveCode,''))" + vbNewLine
        sql += IIf(IsDate(Me.OldVersionDateBefore), " and b.ReceiveCallDate<'" + Me.OldVersionDateBefore + "'", "") + vbNewLine

        sql += "select * from " + temptable + vbNewLine
        sql += " drop table  " + temptable + vbNewLine

        Dim Dtab As DataTable = New DataTable()
        Try
            Dtab = Exec(sql, E_ExecType.DataTable)
            If Dtab.Rows.Count <= 0 Then
                Me.lbMessageRefresh.Text = "沒有歷史來電記錄~"
            End If

            Me.DGV_OldPhone.DataSource = Dtab
            BindDataGridViewCaption(Me.DGV_OldPhone, Me.ReturnCaption(1))

        Catch ex As Exception
            MessageBox.Show(ex.Message + ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            'Me.Cursor = Cursors.Default
        End Try

    End Sub

    Private Sub txt_QuickSearch_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txt_QuickSearch.KeyDown, txt_BoNum.KeyDown, txt_fSaleOrdeNo.KeyDown, txt_CustomerName.KeyDown, txt_CustomerTelphone.KeyDown, txt_fEmployeeId.KeyDown
        If e.KeyCode = Keys.Enter Then
            btnFind_Click(Nothing, Nothing)
        End If
    End Sub

    Private Function FindBonumInfo(ByVal bonum As String) As DataTable
        Dim sql As String = ""
        Dim whereExp As String = " where 1=1 and bonum='" + bonum + "'"
        If isNull(bonum) Then
            whereExp = " where 1<>1 "
        End If
        '新版本的記錄
        sql &= " select fLevel1,ReceiveCallDate,ReceiveCallTime,FullName=(Isnull(c.fName,'') + '/' + Isnull(b.fName,'')),fSaleOrdeNo," + vbNewLine
        sql &= "         Contents,PONum,ListenPsn,CompleteRemark,LastCallBackRemark,Remark,CustomerName,ContactPhone,PurchaseDate,GoodsName," + vbNewLine
        sql &= "         GoodsDescript,DeliveryAddress," + vbNewLine
        sql &= "    BoNum,LastCompleteRemark,LastCallBackTime,a.ItemParentNo,c.fName as ItemParentName,ItemNo,b.fName as ItemName,"
        sql &= "   CompleteStatus=Convert(bit,CompleteStatus),TakeTime,AgentCode,ItemParentNo2,e.fName as ItemParentNo2Name ,ItemNo2,d.fName as ItemNo2Name,Case when Isnull(ItemNo,'')='1101' then Isnull(b.fName,'')+'/'+Isnull(e.fName,'')+'/'+Isnull(d.fName,'') else '' end  as FullName2," + vbNewLine
        sql &= "   CallBackStatus=Convert(Bit,CallBackStatus), LastCallBackDate, LastCallBackPsn,"
        sql &= "   ComplainLevel,SupplierName,EnName,fEmployeeName,DSCTruck,DGKD,DGDelivery,BillStatus, fOperatorPsn, fOperatorDate = Convert(varchar(10), fOperatorDate, 21), fUpdatePsn, fUpdateDate = Convert(varchar(10), fUpdateDate, 21)" + vbNewLine
        sql &= "  from CS_ReceiveInformation   a " & vbCrLf
        sql &= "inner join CS_CusterServiceTypes c on a.ItemParentNo=c.fCode    " + vbNewLine
        sql &= "  left join CS_CusterServiceTypes b on a.ItemNo=b.fCode " + vbNewLine
        sql &= "  left join CS_CusterServiceTypes d on a.ItemNo2=d.fCode left join CS_CusterServiceTypes e on a.ItemParentNo2=e.fCode    " & whereExp + vbNewLine
        sql += IIf(IsDate(Me.NewVersionDateAfter), " and a.ReceiveCallDate>'" + Me.NewVersionDateAfter + "'", "") + vbNewLine
        sql &= " union all " + vbNewLine

        ''查詢以前版本的記錄
        sql &= " select fLevel1,ReceiveCallDate,ReceiveCallTime,FullName=(Isnull(c.fName,'') + '/' + Isnull(b.fName,'')),fSaleOrdeNo," + vbNewLine
        sql &= "         Contents,PONum,ListenPsn,CompleteRemark,LastCallBackRemark,Remark,CustomerName,ContactPhone,PurchaseDate,GoodsName," + vbNewLine
        sql &= "         GoodsDescript,DeliveryAddress," + vbNewLine
        sql &= "    BoNum,LastCompleteRemark,LastCallBackTime,a.ItemParentNo,c.fName as ItemParentName,ItemNo,b.fName as ItemName,"
        sql &= "   CompleteStatus=Convert(bit,CompleteStatus),TakeTime,AgentCode,ItemParentNo2,e.fName as ItemParentNo2Name ,ItemNo2,d.fName as ItemNo2Name,Case when Isnull(ItemNo,'')='1101' then Isnull(b.fName,'')+'/'+Isnull(e.fName,'')+'/'+Isnull(d.fName,'') else '' end  as FullName2," + vbNewLine
        sql &= "   CallBackStatus=Convert(Bit,CallBackStatus), LastCallBackDate, LastCallBackPsn,"
        sql &= "   ComplainLevel,SupplierName,EnName,fEmployeeName,DSCTruck,DGKD,DGDelivery,BillStatus, fOperatorPsn, fOperatorDate = Convert(varchar(10), fOperatorDate, 21), fUpdatePsn, fUpdateDate = Convert(varchar(10), fUpdateDate, 21)" + vbNewLine
        sql &= "  from CS_ReceiveInformation   a " & vbCrLf
        sql &= "inner join CS_CusterServiceType c on a.ItemParentNo=c.fCode    " + vbNewLine
        sql &= "  left join CS_CusterServiceType b on a.ItemNo=b.fCode " + vbNewLine
        sql &= "  left join CS_CusterServiceType d on a.ItemNo2=d.fCode left join CS_CusterServiceType e on a.ItemParentNo2=e.fCode    " & whereExp + vbNewLine
        sql += IIf(IsDate(Me.OldVersionDateBefore), " and a.ReceiveCallDate<'" + Me.OldVersionDateBefore + "'", "") + vbNewLine
        Dim dt As DataTable = Exec(sql, E_ExecType.DataTable, False)
        Return dt
    End Function

    Private Sub cbxDSCTruck1_SelectIndexChange(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxDSCTruck1.SelectedValueChanged
        If cbxDSCTruck1.Tag Is Nothing Then
            Exit Sub
        ElseIf cbxDSCTruck1.SelectedIndex <> -1 Then
            Dim evv As System.Windows.Forms.DataGridViewCellEventArgs = CType(cbxDSCTruck1.Tag, System.Windows.Forms.DataGridViewCellEventArgs)
            Me.DataGridView1.Item(evv.ColumnIndex, evv.RowIndex).Value = cbxDSCTruck1.Text & ""
            cbxDSCTruck1.Visible = False
            cbxDSCTruck1.Tag = Nothing
        End If
    End Sub
    ''来电时间做控制
    Private Sub txtReceiveCallTime_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtReceiveCallTime.Leave
        If ValidateTimeFormat(Me.txtReceiveCallTime.Text) <> True Then
            Me.txtReceiveCallTime.Focus()
            MessageBox.Show("時間格式錯誤，請重新輸入！")
        End If
    End Sub
End Class

